Configure CORS
Your application might need to configure Cross-Origin Resource Sharing (CORS).
Determine If You Actually Need CORS
CORS is only required when your frontend and backend are on different domains or ports.
If you're hosting both your React app and Express server under the same domain (e.g., both on
example.com
), you don't need to configure CORS and can skip to Testing Login and Logout Flows.
Cross-Origin Resource Sharing (CORS) is a security feature that controls how web pages can request resources from different domains. If your React frontend and Express server are hosted on different domains or ports, then you will need to configure CORS to allow React to make requests to Express.
Express Configuration
First, install the CORS middleware in your Express server:
npm install cors
yarn add cors
pnpm add cors
Then configure Express to use CORS:
// app.ts
import express from 'express';
import cors from 'cors';
const app = express();
...
app.use(cors({
origin: 'http://localhost:3000', // Replace value with whatever your React domain/port is.
credentials: true // Required for cookies, authorization headers, etc.
}));
//
// Routes and middlewares come after...
//
...
React Configuration
When making requests from React to Express, ensure you include the credentials configuration in your AJAX client.
Axios
axios.defaults.withCredentials = true;
// ...or...
const apiClient = axios.create({
baseURL: `http://localhost:8080/api`,
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
withCredentials: true, // <-- this
});
Fetch
fetch('http://localhost:8080/api/endpoint', {
credentials: 'include'
})
Your React app can now make authenticated requests to your Express server across different origins.
Now let's test the full authentication flow from end-to-end.
Updated 1 day ago