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 find Express.js tutorials on YouTube?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I use Yarn to add Express.js to my project?
- How can I use the x-forwarded-for header in Express.js?
- How can I use Express.js with TypeScript?
- How can I disable the X-Powered-By header in Express.js?
- How do I use Express.js to create a YouTube clone?
- How can I use an ExpressJS webhook to receive data from an external source?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How can I make an XHR request using Express.js?
See more codes...