The frontend has pages (Chapter S2 15: DevTinder UI - Part 1); now it needs to talk to the backend. In this chapter you'll build the login page, call the API with axios, run into (and properly fix) the famous CORS error, make cookies work between two origins, and keep the logged-in user in Redux Toolkit so every component can use it.
In this chapter you'll learn
- controlled inputs in React, and a working login form
- calling the API with axios, and a
BASE_URLconstant - what an origin is, what CORS is, and how to configure it in Express
- preflight requests, and how
withCredentialsmakes cookies work across origins - Redux Toolkit: store, slice,
Provider,useDispatch,useSelector - showing the logged-in user in the NavBar, and Redux DevTools
Before you start: read Chapter S2 15: DevTinder UI - Part 1 (the React app) and Chapter S2 10: Authentication, JWT & Cookies (the login API and JWT cookie).
Step 1: The login form (controlled inputs)
In a controlled input, React state is the single source of truth for the input's value: the input shows value={state}, and every keystroke updates the state through onChange.
// src/components/Login.jsx
import { useState } from "react";
const Login = () => {
const [emailId, setEmailId] = useState("");
const [password, setPassword] = useState("");
return (
<div className="flex justify-center my-10">
<div className="card bg-base-300 w-96 shadow-sm">
<div className="card-body">
<h2 className="card-title justify-center">Login</h2>
<label className="form-control w-full my-2">
<span className="label-text">Email ID</span>
<input
type="text"
value={emailId}
className="input input-bordered w-full"
onChange={(e) => setEmailId(e.target.value)}
/>
</label>
<label className="form-control w-full my-2">
<span className="label-text">Password</span>
<input
type="password"
value={password}
className="input input-bordered w-full"
onChange={(e) => setPassword(e.target.value)}
/>
</label>
<div className="card-actions justify-center m-2">
<button className="btn btn-primary">Login</button>
</div>
</div>
</div>
</div>
);
};
export default Login;// src/components/Login.jsx
import { useState } from "react";
const Login = () => {
const [emailId, setEmailId] = useState("");
const [password, setPassword] = useState("");
return (
<div className="flex justify-center my-10">
<div className="card bg-base-300 w-96 shadow-sm">
<div className="card-body">
<h2 className="card-title justify-center">Login</h2>
<label className="form-control w-full my-2">
<span className="label-text">Email ID</span>
<input
type="text"
value={emailId}
className="input input-bordered w-full"
onChange={(e) => setEmailId(e.target.value)}
/>
</label>
<label className="form-control w-full my-2">
<span className="label-text">Password</span>
<input
type="password"
value={password}
className="input input-bordered w-full"
onChange={(e) => setPassword(e.target.value)}
/>
</label>
<div className="card-actions justify-center m-2">
<button className="btn btn-primary">Login</button>
</div>
</div>
</div>
</div>
);
};
export default Login;Why controlled? Because the values live in state, you can read them when submitting, validate them while typing, clear them, or pre-fill them, all without touching the DOM directly.
Step 2: Call the API with axios
axios is a popular HTTP client: like the built-in fetch, but it parses JSON automatically, throws on 4xx/5xx status codes (so errors land in catch), and has handy options.
npm install axiosnpm install axiosKeep the backend URL in one place, so you only change it once when you deploy (Chapter S3 02: Nginx and Backend Node App Development):
// src/utils/constants.js
export const BASE_URL = "http://localhost:3000";// src/utils/constants.js
export const BASE_URL = "http://localhost:3000";import axios from "axios";
import { BASE_URL } from "../utils/constants";
const handleLogin = async () => {
try {
const res = await axios.post(BASE_URL + "/login", { emailId, password });
console.log(res.data);
} catch (err) {
console.error(err);
}
};import axios from "axios";
import { BASE_URL } from "../utils/constants";
const handleLogin = async () => {
try {
const res = await axios.post(BASE_URL + "/login", { emailId, password });
console.log(res.data);
} catch (err) {
console.error(err);
}
};Wire it to the button: <button className="btn btn-primary" onClick={handleLogin}>Login</button>.
Click it, and the browser console shows an error like:
Access to XMLHttpRequest at 'http://localhost:3000/login' from origin
'http://localhost:5173' has been blocked by CORS policyAccess to XMLHttpRequest at 'http://localhost:3000/login' from origin
'http://localhost:5173' has been blocked by CORS policyStep 3: Understanding and fixing CORS
What is an origin?
An origin is the combination of protocol + domain + port:
| URL | Origin |
|---|---|
http://localhost:5173/login | http://localhost:5173 |
http://localhost:3000/login | http://localhost:3000, a different origin (different port) |
https://devtinder.com vs http://devtinder.com | different (different protocol) |
The Same-Origin Policy
By default, browsers follow the Same-Origin Policy: JavaScript on one origin may send requests to another origin, but is not allowed to read the response, unless that other server explicitly says it's allowed. This stops a random website from silently reading your bank's API responses using your logged-in cookies.
CORS (Cross-Origin Resource Sharing) is how a server says "this other origin is allowed", through response headers like Access-Control-Allow-Origin.
Fix it in the backend
# in the backend project
npm install cors# in the backend project
npm install cors// src/app.js (backend), before the routers
const cors = require("cors");
app.use(
cors({
origin: "http://localhost:5173", // the frontend's exact origin
credentials: true, // allow cookies to be sent and received
})
);// src/app.js (backend), before the routers
const cors = require("cors");
app.use(
cors({
origin: "http://localhost:5173", // the frontend's exact origin
credentials: true, // allow cookies to be sent and received
})
);Preflight requests
For "non-simple" requests (for example a POST with a JSON body, or with credentials), the browser first sends a preflight: an automatic OPTIONS request asking "may I?". We checked what the cors middleware above answers:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: content-typeHTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: content-typeOnly if the answer allows it does the browser send the real POST.
CORS doesn't protect your API
Here's something even many working developers get wrong. In our test, a request with a different Origin header still reached the server and was processed (status 200). The server just didn't add a matching Access-Control-Allow-Origin, so a browser would refuse to let that page read the response.
So:
- CORS is enforced by browsers only. Postman,
curland other servers ignore it completely. - CORS relaxes the Same-Origin Policy for origins you trust; it's not a security layer for your API.
- Your API's real protection is authentication (JWT), cookie flags (
HttpOnly,Secure,SameSite) and HTTPS (Chapter S2 10: Authentication, JWT & Cookies).
Step 4: Cookies across origins: withCredentials
The login now returns 200, but check the browser's cookies (DevTools → Application → Cookies): the token cookie isn't there, and the next request to /profile/view fails with 401.
By default, cross-origin requests don't include cookies, and the browser ignores Set-Cookie headers in their responses. To change that, both sides must agree:
| Side | Setting | Effect |
|---|---|---|
| Backend | cors({ credentials: true, origin: "<exact origin>" }) | sends Access-Control-Allow-Credentials: true |
| Frontend | axios.post(url, data, { withCredentials: true }) | tells the browser to store cookies from the response, and attach cookies to the request |
const res = await axios.post(
BASE_URL + "/login",
{ emailId, password },
{ withCredentials: true }
);const res = await axios.post(
BASE_URL + "/login",
{ emailId, password },
{ withCredentials: true }
);Important details:
withCredentialscontrols the browser, not the backend. The backend sendsSet-Cookieeither way; withoutwithCredentials, the browser silently drops it.- With credentials,
origincan't be"*": browsers reject a wildcard together with credentials. Use the exact origin. - Add
withCredentials: trueto every API call that needs the login cookie, or set it once:axios.defaults.withCredentials = true.
Step 5: Global state with Redux Toolkit
After login, several components need the user: the NavBar (photo, name), the profile page, the feed. Passing it down through props from component to component gets messy (prop drilling). A global store solves this: any component can read from it.
Redux is the classic global state library; Redux Toolkit (RTK) is its official, much simpler modern form.
npm install @reduxjs/toolkit react-reduxnpm install @reduxjs/toolkit react-reduxFour pieces:
| Piece | Role |
|---|---|
| store | the single object holding all global state |
| slice | one part of the state (e.g. user), plus the functions (reducers) that change it |
dispatch(action) | how components request a change |
useSelector | how components read state (and re-render when it changes) |
The slice
// src/utils/userSlice.js
import { createSlice } from "@reduxjs/toolkit";
const userSlice = createSlice({
name: "user",
initialState: null, // nobody logged in yet
reducers: {
addUser: (state, action) => action.payload, // replace state with the user
removeUser: () => null, // logout (next chapter)
},
});
export const { addUser, removeUser } = userSlice.actions;
export default userSlice.reducer;// src/utils/userSlice.js
import { createSlice } from "@reduxjs/toolkit";
const userSlice = createSlice({
name: "user",
initialState: null, // nobody logged in yet
reducers: {
addUser: (state, action) => action.payload, // replace state with the user
removeUser: () => null, // logout (next chapter)
},
});
export const { addUser, removeUser } = userSlice.actions;
export default userSlice.reducer;createSlice generates the action creators (addUser, removeUser) and the reducer for you.
The store
// src/utils/appStore.js
import { configureStore } from "@reduxjs/toolkit";
import userReducer from "./userSlice";
const appStore = configureStore({
reducer: {
user: userReducer,
},
});
export default appStore;// src/utils/appStore.js
import { configureStore } from "@reduxjs/toolkit";
import userReducer from "./userSlice";
const appStore = configureStore({
reducer: {
user: userReducer,
},
});
export default appStore;Provide it to the app
// src/App.jsx
import { Provider } from "react-redux";
import appStore from "./utils/appStore";
function App() {
return (
<Provider store={appStore}>
<BrowserRouter basename="/">
{/* ...routes from S2 15... */}
</BrowserRouter>
</Provider>
);
}// src/App.jsx
import { Provider } from "react-redux";
import appStore from "./utils/appStore";
function App() {
return (
<Provider store={appStore}>
<BrowserRouter basename="/">
{/* ...routes from S2 15... */}
</BrowserRouter>
</Provider>
);
}Dispatch on login, then go to the feed
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { addUser } from "../utils/userSlice";
const dispatch = useDispatch();
const navigate = useNavigate();
const [error, setError] = useState("");
const handleLogin = async () => {
try {
const res = await axios.post(
BASE_URL + "/login",
{ emailId, password },
{ withCredentials: true }
);
dispatch(addUser(res.data)); // store the user (the login API returns it)
navigate("/"); // go to the feed
} catch (err) {
setError(err?.response?.data || "Something went wrong"); // show the API's message
}
};import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { addUser } from "../utils/userSlice";
const dispatch = useDispatch();
const navigate = useNavigate();
const [error, setError] = useState("");
const handleLogin = async () => {
try {
const res = await axios.post(
BASE_URL + "/login",
{ emailId, password },
{ withCredentials: true }
);
dispatch(addUser(res.data)); // store the user (the login API returns it)
navigate("/"); // go to the feed
} catch (err) {
setError(err?.response?.data || "Something went wrong"); // show the API's message
}
};Show {error} under the inputs, e.g. <p className="text-red-500">{error}</p>. (For res.data to be the user, change the end of the backend's login route (Chapter S2 10: Authentication, JWT & Cookies) from res.send("Login successful!") to send the user without the password hash: const { password, ...safeUser } = user.toObject(); res.send(safeUser);.)
We built this exact store, slice and login component in a test project (React 19, Redux Toolkit 2, React Router 7) to make sure it compiles.
Read it in the NavBar
import { useSelector } from "react-redux";
const NavBar = () => {
const user = useSelector((store) => store.user);
return (
<div className="navbar bg-base-300 shadow-sm">
{/* ...logo... */}
{user && (
<div className="flex-none gap-2 items-center">
<p>Welcome, {user.firstName}</p>
<img alt="user photo" src={user.photoUrl} className="w-10 rounded-full" />
</div>
)}
</div>
);
};import { useSelector } from "react-redux";
const NavBar = () => {
const user = useSelector((store) => store.user);
return (
<div className="navbar bg-base-300 shadow-sm">
{/* ...logo... */}
{user && (
<div className="flex-none gap-2 items-center">
<p>Welcome, {user.firstName}</p>
<img alt="user photo" src={user.photoUrl} className="w-10 rounded-full" />
</div>
)}
</div>
);
};When addUser runs, every component that useSelectors store.user re-renders automatically, with no page refresh.
Install the Redux DevTools browser extension. It shows every dispatched action and the state before and after, which is great for debugging.
What NOT to put in Redux: the token
With the cookie approach, the browser holds the JWT and sends it automatically. If the cookie is HttpOnly (it should be: Chapter S2 10: Authentication, JWT & Cookies), JavaScript can't even read it. Store only the user profile in Redux. Copying the token into JavaScript-accessible state (Redux or localStorage) brings back exactly the XSS risk that HttpOnly protects against.
Common mistakes
- Fixing CORS in the frontend: impossible; it's configured on the server.
origin: "*"withcredentials: true: the browser rejects it.- Forgetting
withCredentials: trueon later calls: requests arrive without the cookie → 401. cors()registered after the routers: no CORS headers on those routes.- Storing the JWT in Redux or
localStorage. - Not wrapping the app in
<Provider>:useSelectorthrows.
Key takeaways
- Controlled inputs keep form values in React state.
- axios calls the API; keep the backend URL in a
BASE_URLconstant. - An origin = protocol + domain + port. The browser's Same-Origin Policy blocks reading cross-origin responses unless the server allows it with CORS headers.
- Configure CORS on the backend:
cors({ origin: "<exact frontend origin>", credentials: true }). - Cookies across origins need
withCredentials: truein the frontend andcredentials: truein CORS. - CORS is browser-only; it's not API security.
- Redux Toolkit:
createSlice+configureStore+<Provider>; write withdispatch, read withuseSelector. Store the user, never the token.
Interview questions
Q1. What is CORS?
Cross-Origin Resource Sharing is a browser mechanism that lets a server declare which other origins may read its responses, via headers like Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Credentials. Without them, the browser's Same-Origin Policy blocks JavaScript on another origin from reading the response.
Q2. What is a preflight request?
An automatic OPTIONS request the browser sends before certain cross-origin requests (non-simple methods like PUT/PATCH/DELETE, custom headers, Content-Type: application/json, or credentials) to ask whether the real request is allowed. The server answers with CORS headers; only if they permit it does the browser send the actual request.
Q3. Does CORS protect your API from unauthorized access?
No. CORS is enforced only by browsers, and it only controls whether a page from another origin may read responses. Requests still reach the server, and non-browser clients (curl, Postman, scripts) ignore CORS entirely. API security comes from authentication, authorization, CSRF protection and HTTPS.
Q4. How do you send cookies with cross-origin requests?
The client must opt in: fetch(url, { credentials: "include" }) or axios { withCredentials: true }. The server must respond with Access-Control-Allow-Credentials: true and a specific Access-Control-Allow-Origin (not *). The cookie itself must also allow it: SameSite=None; Secure if the sites are truly cross-site (different domains).
Q5. What is Redux, and why use Redux Toolkit?
Redux is a predictable global state container: state lives in one store, components dispatch actions, and pure reducers compute the new state. Redux Toolkit is the official recommended way to write Redux: configureStore sets up the store with good defaults (DevTools, checks), and createSlice generates actions and reducers and lets you write "mutating" logic safely (it uses Immer). It removes most of classic Redux's boilerplate.
Q6. What is prop drilling, and how do you avoid it?
Passing props through several layers of components that don't use them, just so a deeply nested child can. It makes code harder to change. Avoid it with React Context (for simple, rarely-changing values) or a state library like Redux Toolkit or Zustand, so components read shared state directly.
Q7. What is a controlled component in React?
A form element whose value is driven by React state (value={state}) and updated through onChange. React state is the single source of truth, which makes validation, conditional logic and resetting easy. In an uncontrolled component, the DOM keeps the value and you read it with a ref.
What's next
Login works, but refreshing the page logs you out (Redux lives in memory), and anyone can open /profile. In Chapter S2 17: DevTinder UI - Part 3 you'll restore the session on page load, protect pages, add logout, and build the feed and edit profile pages.