Configuring Refresh Tokens with Express and React: A 2026 Guide

Discover how to configure refresh tokens with Express and React using cookies. Enhance your app's security by managing user sessions efficiently.

Configuring Refresh Tokens with Express and React: A 2026 Guide

Configuring Refresh Tokens with Express and React: A 2026 Guide

In modern web applications, managing user authentication efficiently is crucial for enhancing security and user experience. One common approach is to use tokens, specifically refresh tokens, to maintain user sessions. This guide will walk you through configuring refresh tokens in an Express backend and a React frontend using cookies.

Key Takeaways

  • Implement secure token-based authentication using refresh tokens.
  • Configure Express to send and manage cookies for token storage.
  • Integrate refresh token logic in React for session management.
  • Debug common issues with token handling in cookies.

Prerequisites

Before you begin, ensure you have the following:

  • Basic knowledge of JavaScript and Node.js.
  • Understanding of Express.js and React basics.
  • Node.js (v18) and npm installed.
  • Basic setup of an Express server and React application.

Step 1: Setup Express Server

First, let's set up a basic Express server. This will handle login and refresh token logic.

const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json()); // Parse JSON bodies

const REFRESH_TOKEN_SECRET = 'your-refresh-token-secret'; // Use a strong secret
const ACCESS_TOKEN_SECRET = 'your-access-token-secret';

const users = [
  { id: 1, email: 'user@example.com', password: 'password' }
];

function generateAccessToken(user) {
  return jwt.sign(user, ACCESS_TOKEN_SECRET, { expiresIn: '15m' });
}

let refreshTokens = [];

app.post('/login', (req, res) => {
  const { email, password } = req.body;
  const user = users.find(u => u.email === email && u.password === password);
  if (!user) return res.status(401).send('Email or password incorrect');

  const accessToken = generateAccessToken({ id: user.id });
  const refreshToken = jwt.sign({ id: user.id }, REFRESH_TOKEN_SECRET);
  refreshTokens.push(refreshToken);
  res.cookie('refreshToken', refreshToken, { httpOnly: true, secure: true });
  res.json({ accessToken });
});

Step 2: Implement Refresh Token API

Next, implement an API to handle refresh token logic. This API will issue new access tokens.

app.post('/token', (req, res) => {
  const refreshToken = req.cookies.refreshToken;
  if (!refreshToken || !refreshTokens.includes(refreshToken)) {
    return res.status(403).send('Refresh token not found, login again');
  }
  jwt.verify(refreshToken, REFRESH_TOKEN_SECRET, (err, user) => {
    if (err) return res.status(403).send('Invalid refresh token');
    const accessToken = generateAccessToken({ id: user.id });
    res.json({ accessToken });
  });
});

Step 3: React Application Setup

Now, configure the React frontend to handle token-based authentication.

import React, { useState } from 'react';
import axios from 'axios';

function App() {
  const [accessToken, setAccessToken] = useState('');

  const login = async () => {
    try {
      const response = await axios.post('/login', {
        email: 'user@example.com',
        password: 'password'
      });
      setAccessToken(response.data.accessToken);
    } catch (error) {
      console.error('Login failed:', error);
    }
  };

  const refreshAccessToken = async () => {
    try {
      const response = await axios.post('/token');
      setAccessToken(response.data.accessToken);
    } catch (error) {
      console.error('Token refresh failed:', error);
    }
  };

  return (
    
      Login
      Refresh Token
      Access Token: {accessToken}
    
  );
}

export default App;

Step 4: Test and Debug

Run both the Express server and React application. Use the browser's developer tools to inspect cookies and network requests. Ensure the refresh token is stored as a secure HTTP-only cookie.

Common Errors/Troubleshooting

If you don't see the cookie in the browser:

  • Ensure the cookie is set with the correct domain and path settings.
  • Check that the server is running on HTTPS if using the secure flag.
  • Verify that the httpOnly flag is properly set to prevent client-side access.

Frequently Asked Questions

Why use refresh tokens?

Refresh tokens allow maintaining user sessions without re-authenticating, improving security and user experience.

How do I store the refresh token securely?

Store the refresh token in an HTTP-only, secure cookie to prevent client-side access.

What if my refresh token is compromised?

Implement token revocation and monitor for suspicious activity to mitigate risks.

Frequently Asked Questions

Why use refresh tokens?

Refresh tokens allow maintaining user sessions without re-authenticating, improving security and user experience.

How do I store the refresh token securely?

Store the refresh token in an HTTP-only, secure cookie to prevent client-side access.

What if my refresh token is compromised?

Implement token revocation and monitor for suspicious activity to mitigate risks.