Skip to content

Instantly share code, notes, and snippets.

@faisal-foyez
Last active February 19, 2023 03:11
Show Gist options
  • Save faisal-foyez/c01effd9cb908ac64cc3c5813cba2e11 to your computer and use it in GitHub Desktop.
Save faisal-foyez/c01effd9cb908ac64cc3c5813cba2e11 to your computer and use it in GitHub Desktop.
Cookies in gist

Cookies with node example

Step 1 - Set a cookie

app.get('/setcookie', (req, res) => {
    res.cookie(`Cookie token name`,`encrypted cookie string Value`);
    res.send('Cookie have been saved successfully');
});

Step 2 - Using the req.cookies method to check the saved cookies

// get the cookie incoming request
app.get('/getcookie', (req, res) => {
    //show the saved cookies
    console.log(req.cookies)
    res.send(req.cookies);
});

bold

Step 3 - Secure cookies

  1. HTTPonly ensures that a cookie is not accessible using the JavaScript code. This is the most crucial form of protection against cross-scripting attacks.

  2. A secure attribute ensures that the browser will reject cookies unless the connection happens over HTTPS.

  3. sameSite attribute improves cookie security and avoids privacy leaks. By default, sameSite was initially set to none (sameSite = None). This allowed third parties to track users across sites. Currently, it is set to Lax (sameSite = Lax) meaning a cookie is only set when the domain in the URL of the browser matches the domain of the cookie, thus eliminating third party’s domains. sameSite can also be set to Strict (sameSite = Strict).

app.get('/setcookie', (req, res) => {
    res.cookie(`Cookie token name`,`encrypted cookie string Value`,{
        maxAge: 5000,
        // expires works the same as the maxAge
        expires: new Date('01 12 2021'),
        secure: true,
        httpOnly: true,
        sameSite: 'lax'
    });
    res.send('Cookie have been saved successfully');
});

Step 4 - Deleting a cookie

// delete the saved cookie
app.get('/deletecookie', (req, res) => {
    //show the saved cookies
    res.clearCookie()
    res.send('Cookie has been deleted successfully');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment