DEV Community

Cover image for Quick Cookie Management Tips
INDRANIL MAITI
INDRANIL MAITI

Posted on

Quick Cookie Management Tips

Hey there, fellow developers! 👋
You know what's funny? I recently hit a roadblock with cookie management in my recent project

, After figuring it out, I thought - "Hey, others might run into this too!" So here I am, sharing what I learned about making cookies work smarter, not harder.
Let me show you how to level up your cookie game!

What is cookie

A cookie (also known as a web cookie or browser cookie) is a small piece of data a server sends to a user's web browser. The browser may store cookies, create new cookies, modify existing ones, and send them back to the same server with later requests.
-- This is primarily used for session management, personalization and tracking.

The Cookie Basics

Think of cookies as small data packets your server sends to users' browsers. They're super handy for things like keeping users logged in or remembering their preferences.

Server-Side Cookie Configuration:

const options = {
        httpOnly: true,
        secure: true,
        sameSite: "none"
    }

    return res
    .status(200)
    .cookie("accessToken", accessToken, options)
    .cookie("refreshToken", refreshToken, options)
    .json(
        new Apiresponse(
            200, 
            {
                user: loggedInUser
            },
            "User logged In Successfully"
        )
    )
Enter fullscreen mode Exit fullscreen mode

Here is a simple example of how you can send cookies from your server to browser.
Here, I have set two cookies in the response:

  1. An access token for short-term authentication
  2. A refresh token for getting new access tokens

In the 'options' I have taken httpOnly, secure, sameSite. These are essential options to set your cookie parameters and security.
These options create secure cookies:

  • httpOnly: true prevents client-side JavaScript from accessing the cookie, protecting against XSS attacks

  • secure: true ensures cookies are only transmitted over HTTPS

  • sameSite: "none" allows the cookie to be sent in cross-origin requests, which is needed for your frontend-backend communication
    I was actually having problems in this sameSite parameter

Client-Side Cookie Handling:

const loginResponse = await axios.post(
    `${base_URL}/api/v1/users/signin`,
    { email, password },
    { withCredentials: true }
);

if (loginResponse.data.data) {
    const userResponse = await axios.get(
        `${base_URL}/api/v1/users/getuser`,
        { 
            withCredentials: true  // This will automatically send the cookies
        }
    );
}

Enter fullscreen mode Exit fullscreen mode

In the client side, when the user is loggedin a cookie is sent from the server to browser and _loginResponse_ become true then I am sending a request to my server to get the cookie from browser using _withCredentials: true_ and make a database query. As a response I get the user data.

That's simple and easy right?

What other options in cookie

const options = {
    expires: new Date(Date.now() + 24 * 60 * 60 * 1000), // Expires in 24 hours
    maxAge: 24 * 60 * 60 * 1000, // Alternative way to set expiry in milliseconds
    domain: '.example.com',    // Cookie available on all subdomains
    path: '/',                 // Cookie available for entire domain

}
Enter fullscreen mode Exit fullscreen mode
  • expires vs maxAge: Use either one, not both. maxAge is generally preferred as it's relative to the current time
    domain: Be careful with this setting as it affects security. Only set it if you need cross-subdomain access

  • sameSite:
    'strict' is most secure but restricts cross-site requests
    'lax' is a good default
    'none' requires secure: true

  • 'signed': Requires your server to have a secret key configured
    partitioned: New feature for privacy, not supported by all browsers yet.

That's all from my side. Hope this helps. Also this is my first article so expects some roasting from you guys.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
crazyboyze profile image
crazyboyze • • Edited

Manage cookies by clearing them regularly, using browser settings to block third-party tracking, and enabling only essential ones for smoother browsing. This ensures better privacy while checking updates like Champions Trophy 2025 semi-final and final match dates including group matches, knockouts, and the highly anticipated final. Stay secure while following cricket schedules hassle-free!