Skip to content

Instantly share code, notes, and snippets.

@faisal-foyez
Last active February 19, 2023 03:11
Show Gist options
  • Select an option

  • Save faisal-foyez/c01effd9cb908ac64cc3c5813cba2e11 to your computer and use it in GitHub Desktop.

Select an option

Save faisal-foyez/c01effd9cb908ac64cc3c5813cba2e11 to your computer and use it in GitHub Desktop.

Revisions

  1. faisal-foyez renamed this gist Feb 19, 2023. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. faisal-foyez revised this gist Feb 19, 2023. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions Readme.md
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,4 @@
    # Cookies with node example
    ### Step 1 - Set a cookie
    ```
    app.get('/setcookie', (req, res) => {
  3. faisal-foyez created this gist Feb 19, 2023.
    55 changes: 55 additions & 0 deletions Readme.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    ### 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');
    });
    ```