How to Set Cookie in Express: Simple Guide with Examples
In Express, you set a cookie using the
res.cookie(name, value, options) method inside a route handler. This method attaches a cookie to the HTTP response that the browser will store and send back on future requests.Syntax
The res.cookie() method sets a cookie on the response. It takes three main parts:
- name: The cookie's name as a string.
- value: The cookie's value as a string or object.
- options (optional): An object to customize the cookie, like
maxAge,httpOnly, andsecure.
javascript
res.cookie(name, value, options)
Example
This example shows a simple Express server that sets a cookie named user with value John when you visit the root URL. The cookie lasts for one day and is HTTP-only for security.
javascript
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.cookie('user', 'John', { maxAge: 24 * 60 * 60 * 1000, httpOnly: true }); res.send('Cookie has been set'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
When visiting http://localhost:3000, the browser receives a cookie named 'user' with value 'John'.
Common Pitfalls
Common mistakes when setting cookies in Express include:
- Not using
httpOnlyfor sensitive cookies, which can expose them to client-side scripts. - Forgetting to set
secure: truewhen using HTTPS, which ensures cookies are sent only over secure connections. - Setting cookies after sending the response body, which won't work because headers are already sent.
- Not parsing cookies on incoming requests if you want to read them (use
cookie-parsermiddleware).
javascript
/* Wrong: Setting cookie after sending response */ app.get('/wrong', (req, res) => { res.send('Hello'); res.cookie('test', 'fail'); // This will not work }); /* Right: Set cookie before sending response */ app.get('/right', (req, res) => { res.cookie('test', 'success'); res.send('Cookie set correctly'); });
Quick Reference
Tips for setting cookies in Express:
- Use
res.cookie(name, value, options)to set cookies. - Set
httpOnly: trueto protect cookies from JavaScript access. - Use
maxAgeorexpiresto control cookie lifetime. - Set
secure: truewhen using HTTPS to enhance security. - Remember to set cookies before sending the response body.
Key Takeaways
Use res.cookie(name, value, options) inside route handlers to set cookies in Express.
Always set httpOnly: true for cookies that should not be accessible by client-side scripts.
Set cookies before sending the response body to ensure headers are not already sent.
Use secure: true when your site uses HTTPS to protect cookie data during transmission.
Use maxAge or expires options to control how long the cookie lasts in the browser.