expressjsHow do I use cookies with Express.js?
Cookies are small pieces of data stored in the browser of a user that can be used to identify the user and enable user-specific functionality in the application. Express.js provides a middleware to handle cookie-based authentication.
To use cookies with Express.js, first install the cookie-parser middleware:
npm install cookie-parser
Then, add the cookie-parser middleware to your Express.js application:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
Now, you can set and get cookies from the request and response objects:
// Set cookie
res.cookie('name', 'value', { maxAge: 3600 });
// Get cookie
const name = req.cookies.name;
The code above sets a cookie with the name name
and the value value
that will expire after one hour. You can also use the cookie-parser middleware to sign and verify cookies.
Helpful links
More of Expressjs
- How do I download a zip file using Express.js?
- How do I find Express.js tutorials on YouTube?
- How do I use adm-zip with Express.js?
- How do I download a zip file using Express.js?
- How can I use Zipkin to trace requests in Express.js?
- How do I use Zod with Express.js?
- How can I disable the X-Powered-By header in Express.js?
- How do I set the keepalivetimeout in Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How can I use Express.js to develop a web application?
See more codes...