Secure React Apps Against XSS with HttpOnly Cookies
In this article
Using HttpOnly cookies in React applications helps protect against cross-site scripting (XSS) attacks by preventing client-side JavaScript from accessing sensitive session tokens. When combined with secure backend practices, this approach ensures that even if malicious scripts are injected, they cannot steal session data. This guide walks through implementing HttpOnly cookies in a full-stack React app to enhance security.
What You'll Need
- A React application (created with Create React App or Vite)
- A backend server (Node.js with Express recommended)
- Basic knowledge of HTTP cookies and CORS
- HTTPS in production (required for secure cookie flags)
- A tool like Postman or curl to test API endpoints
Step-by-Step
- Set up a backend server: Create a Node.js server using Express. This server will handle authentication and securely set cookies. Install Express and necessary middleware:
npm install express cors cookie-parser dotenv. - Enable CORS with credentials: In your Express app, configure CORS to allow credentials from your React frontend. Use
app.use(cors({ origin: 'http://localhost:3000', credentials: true }));to permit requests from your React app and allow cookie transmission. - Parse cookies: Use
cookie-parsermiddleware to parse incoming cookies:app.use(cookieParser());. This allows your backend to read cookies sent by the client. - Create a login endpoint: Implement a POST route (e.g.,
/api/login) that authenticates a user. On successful login, set a session token or JWT in an HttpOnly cookie:res.cookie('token', jwtToken, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'strict', maxAge: 24 * 60 * 60 * 1000 // 1 day }); res.json({ success: true }); - Verify authentication on protected routes: Create middleware to check for the HttpOnly cookie on authenticated routes. Extract the token from
req.cookies.tokenand validate it. Send a 401 error if invalid or missing. - Send credentials from React: When making requests from your React app to the backend, ensure
fetchoraxiosincludes credentials. For fetch:fetch('/api/profile', { method: 'GET', credentials: 'include' });For axios:axios.get('/api/profile', { withCredentials: true }); - Log out securely: Create a logout endpoint on the backend that clears the cookie:
res.clearCookie('token'); res.json({ success: true });. Call this from React using a fetch request withcredentials: 'include'. - Use HTTPS in production: Ensure your production deployment uses HTTPS. The
securecookie flag only works over HTTPS, preventing cookie transmission over unencrypted connections. - Validate input on the server: Never trust client input. Sanitize and validate all data received by the backend to reduce XSS risks even further.
- Avoid rendering user input directly: In React, never use
dangerouslySetInnerHTMLwith untrusted content. If unavoidable, sanitize with a library like DOMPurify before rendering.
Common Mistakes
- Forgetting
credentials: 'include': Without this, cookies won't be sent with cross-origin requests, breaking authentication. - Missing
httpOnly: true: If omitted, JavaScript can access the cookie viadocument.cookie, defeating the protection. - Not setting
secure: truein production: Cookies may be sent over HTTP, exposing them to interception. - Incorrect CORS configuration: Allowing all origins or not enabling credentials can lead to security gaps or broken functionality.
- Using
localStoragefor tokens: Storing tokens inlocalStoragemakes them accessible to XSS scripts. HttpOnly cookies are safer.
Tips
- Use
sameSite: 'strict'or'lax': Prevents CSRF attacks by controlling when cookies are sent with cross-site requests. - Shorten cookie lifetime: Reduce
maxAgeto limit the window of opportunity for misuse. - Rotate tokens: Issue new tokens on login and invalidate old ones to minimize exposure.
- Log failed authentication attempts: Monitor for brute force or suspicious activity.
- Test with browser dev tools: Verify the cookie appears in the Application tab and lacks the
HttpOnlyflag.
Troubleshooting
If authentication fails despite correct code, check the browser's developer tools. Under the Network tab, inspect the login response to confirm the Set-Cookie header includes HttpOnly and Secure (in production). If the cookie isn't sent on subsequent requests, ensure credentials: 'include' is used and CORS is properly configured. If you see CORS errors, verify the origin in the backend CORS settings matches your React app's URL exactly. For localhost mismatches, ensure ports (e.g., 3000) are correct. If cookies are not saved, check that the response is not being cached or intercepted by middleware. In production, confirm HTTPS is active—cookies with the secure flag won't be set over HTTP.
Frequently Asked Questions
Can HttpOnly cookies prevent all XSS attacks?
No. HttpOnly cookies prevent theft of session tokens via XSS, but they don't stop scripts from performing actions on behalf of the user if already authenticated.
Why can't JavaScript read HttpOnly cookies?
The browser enforces this by design. Only HTTP(S) requests automatically include HttpOnly cookies; JavaScript's document.cookie cannot access them.
Is it safe to store JWTs in HttpOnly cookies?
Yes, as long as the cookie is also secure and sameSite is set. This prevents network interception and CSRF.
Do I still need CSRF protection with HttpOnly cookies?
Yes. While sameSite: 'strict' helps, additional CSRF tokens or double-submit cookies add defense in depth.
Can React read an HttpOnly cookie?
No. React runs in the browser and cannot access HttpOnly cookies. Authentication state must be inferred from API responses.
What happens if I forget the credentials option?
The browser won't send cookies with the request, so the server won't recognize the user as logged in, leading to authentication failures.