Set cookie and run function if found - EJS

i need the page to run a function if a cookie is found, how can i do this with EJS?

I would grab the cookies in express, using the cookie-parser middleware. Install cookie-parser from npm, then:

app.use(require("cookie-parser")())

That populates the req.cookies property with the cookies from the request. Then, in the route, you can do something with the cookies:

app.get("/route", (req, res) => {
  if(req.cookies.token) {
    // run code
  }

  // ejs render
  // pass cookies in as a variable to the view
  res.render("my_view", { cookies: req.cookies})
})
1 Like

[REDACTED]

to fetch cookies without extra library;

function parseCookies (request) {
    let result = {};
    var rc = request.headers.cookie;

    rc && rc.split(';').forEach(function( cookie ) {
        var parts = cookie.split('=');
        result[parts.shift().trim()] = decodeURI(parts.join('='));
    });

    return result;
}

you can then check if the resulting object has the attributes you are looking for in the cookies.