Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

Express res.cookie() Method

Updated on Oct 28, 2024
By Mari Selvan
👁️ 292 - Views
⏳ 4 mins
💬 1 Comment
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:

syntax.js
Copied
Copy To Clipboard
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.

example.js
Copied
Copy To Clipboard
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.

example.js
Copied
Copy To Clipboard
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.

example.js
Copied
Copy To Clipboard
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

  1. 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.js
    Copied
    Copy To Clipboard
    res.cookie('sessionID', '123456', { secure: true, httpOnly: true });
  2. 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.js
    Copied
    Copy To Clipboard
    res.cookie('user', 'john_doe', { maxAge: 900000 });
    // or
    res.cookie('user', 'john_doe', { expires: new Date(Date.now() + 900000) });
  3. 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.js
    Copied
    Copy To Clipboard
    // 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:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

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

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mari Selvan
Mari Selvan
8 months ago

If you have any doubts regarding this article (Express res.cookie() Method), please comment here. I will help you immediately.

We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy