Home > Web Front-end > JS Tutorial > Quick Cookie Management Tips

Quick Cookie Management Tips

Susan Sarandon
Release: 2025-01-29 22:36:12
Original
892 people have browsed it

Quick Cookie Management Tips

Hey developers! I recently wrestled with cookie management in my project, e-commerce-smoky-omega.vercel.app, and thought I'd share my learnings. Let's make cookies work smarter!

What are Cookies?

A cookie is a small data packet sent from a server to a user's browser. Browsers store, create, modify, and resend these to the server with subsequent requests. This is crucial for session management, personalization, and tracking.

Cookie Essentials

Think of cookies as small notes your server leaves in the user's browser. They're perfect for keeping users logged in or remembering their preferences.

Server-Side Cookie Setup

<code class="language-javascript">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"
        )
    );</code>
Copy after login

This example shows setting two cookies: an access token (short-term authentication) and a refresh token (for obtaining new access tokens). The options object configures crucial security parameters:

  • httpOnly: true: Prevents client-side JavaScript access, mitigating XSS attacks.
  • secure: true: Ensures cookies are only sent over HTTPS.
  • sameSite: "none": Allows cookies in cross-origin requests (essential for frontend-backend communication). I initially struggled with this setting.

Client-Side Cookie Handling

<code class="language-javascript">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 } // Automatically sends cookies
    );
}</code>
Copy after login

After a successful login (server sends cookies), withCredentials: true in the client-side request ensures the browser sends the cookies back to the server for user data retrieval. Simple, right?

Advanced Cookie Options

<code class="language-javascript">const options = {
    expires: new Date(Date.now() + 24 * 60 * 60 * 1000), // Expires in 24 hours
    maxAge: 24 * 60 * 60 * 1000, // Alternative expiry (milliseconds)
    domain: '.example.com',    // All subdomains
    path: '/',                 // Entire domain

};</code>
Copy after login
  • expires vs maxAge: Use one, not both. maxAge (milliseconds since now) is generally preferred.
  • domain: Use cautiously due to security implications. Only set if cross-subdomain access is needed.
  • sameSite: strict (most secure, limits cross-site requests), lax (good default), none (requires secure: true).
  • signed: Requires a server-side secret key.
  • partitioned: A newer privacy feature, not universally supported.

That's it! Hope this helps. This is my first article, so feedback is welcome!

The above is the detailed content of Quick Cookie Management Tips. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template