Express.js Basic
- express Intro
- express express()
- express Application
- express Request
- express Response
Properties
Methods
- express Router
Express res.cookie() Method
Photo Credit to CodeToFun
🙋 Introduction
Cookies play a crucial role in web development, enabling server-side storage of information on the client's browser. In Express.js, the res.cookie()
method provides a straightforward way to set cookies in the HTTP response.
In this guide, we'll explore the syntax, usage, and practical examples of the res.cookie()
method to manage cookies effectively in your Express.js applications.
💡 Syntax
The syntax for the res.cookie()
method is simple:
res.cookie(name, value, [options])
- name: A string representing the name of the cookie.
- value: The value to be stored in the cookie.
- options: An optional object containing additional cookie options such as expiration, domain, path, etc.
🍬 Setting Cookies
With res.cookie()
, you can set cookies in the response to be sent to the client's browser.
app.get('/set-cookie', (req, res) => {
res.cookie('user', 'john_doe', { maxAge: 900000, httpOnly: true });
res.send('Cookie set successfully!');
});
In this example, the /set-cookie route sets a cookie named 'user' with the value 'john_doe' and additional options like maxAge (expiration time) and httpOnly (accessible only through HTTP).
🍪 Retrieving Cookies
Once set, cookies can be retrieved from subsequent requests, allowing you to personalize user experiences based on stored information.
app.get('/get-cookie', (req, res) => {
const username = req.cookies.user;
res.send(`Welcome back, ${username}!`);
});
In this example, the /get-cookie route retrieves the 'user' cookie previously set and uses its value to personalize the response.
🍩 Cookie Options
The options parameter in res.cookie()
allows you to configure various aspects of the cookie.
app.get('/custom-cookie', (req, res) => {
res.cookie('preferences', { theme: 'dark', language: 'en' }, { maxAge: 86400000, secure: true });
res.send('Custom cookie set successfully!');
});
Here, a custom object is stored in a cookie named 'preferences,' and additional options like maxAge and secure are applied.
🏆 Best Practices
Use Secure and HttpOnly Flags:
Always consider setting the secure flag for cookies transmitted over HTTPS and the httpOnly flag to prevent client-side access via JavaScript.
example.jsCopiedres.cookie('sessionID', '123456', { secure: true, httpOnly: true });
Set Max-Age or Expires:
Define an expiration time for cookies using the maxAge option or expires option to enhance security and manage cookie persistence.
example.jsCopiedres.cookie('user', 'john_doe', { maxAge: 900000 }); // or res.cookie('user', 'john_doe', { expires: new Date(Date.now() + 900000) });
Use Signed Cookies for Enhanced Security:
Consider using signed cookies to add an extra layer of security, ensuring that the cookie values have not been tampered with.
example.jsCopied// Enable cookie signing when initializing Express app const secretKey = 'yourSecretKey'; app.use(cookieParser(secretKey)); // Set a signed cookie res.cookie('sessionId', '123456', { signed: true });
🎉 Conclusion
The res.cookie()
method in Express.js provides a convenient way to manage cookies, enhancing the functionality and personalization of your web applications. Understanding its syntax, usage, and best practices will empower you to implement secure and effective cookie management in your Express.js projects.
Now, go ahead and leverage the res.cookie()
method to create dynamic and personalized web experiences for your users!
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (Express res.cookie() Method), please comment here. I will help you immediately.