When working with tokens in a MERN (MongoDB, Express.js, React.js, Node.js) stack, storing a token in cookies is a common practice, especially for maintaining user sessions. Here's how you can store a token in cookies and retrieve it:
Storing Token in Cookies
Server-side (Node.js/Express):
After user authentication, you can send the token as a cookie from the server. Use the cookie-parser middleware to parse incoming cookies, and res.cookie() method to set a cookie.
const express = require('express');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken'); // Assuming you're using JWT
const app = express();
app.use(cookieParser());
// Your JWT Secret
const JWT_SECRET = 'your_secret_key';
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Validate user credentials (this is just a placeholder)
if (username === 'user' && password === 'pass') {
// Create a token
const token = jwt.sign({ id: 'user_id' }, JWT_SECRET, { expiresIn: '1h' });
// Set the token as a cookie
res.cookie('token', token, { httpOnly: true, secure: true, sameSite: 'strict' });
res.status(200).send({ message: 'Login successful' });
} else {
res.status(401).send({ message: 'Invalid credentials' });
}
});
httpOnly: The cookie cannot be accessed via JavaScript, enhancing security.
secure: The cookie is only sent over HTTPS.
sameSite: Helps to protect against cross-site request forgery (CSRF) attacks.
Client-side (React):
When dealing with cookies on the client side, you might not need to handle the token directly unless you have specific client-side operations. Cookies tagged with httpOnly cannot be accessed via client-side JavaScript for security reasons.
Retrieving Token from Cookies
Server-side:
To retrieve and verify the token from cookies on subsequent requests, use middleware in Express.
If you set up cookies correctly (httpOnly), you won't access them directly via JavaScript. For making requests to the server, ensure that browsers include cookies by setting credentials: 'include' in fetch requests if needed.
This setup should help securely store and retrieve your tokens using cookies within a MERN stack application. Always remember to take additional security measures in production environments, such as using HTTPS and setting appropriate cookie attributes.