0

I have to do an app for the university ( and I'm not allowed to use express or other similar modules ) and I was wondering how do you specify the route on which you write a cookie. Why ?

So far I've noticed that cookies are stored mainly on domains, but if u set a cookie on localhost:3000/ the cookie will be on the subroutes too, however if you set a cookie on localhost:3000/someroute, then that cookie won't be on "/" .

So how do you set a cookie on "/" when you are on "/someRoute" and as well how can you delete a cookie ?

This is how I've been writing on cookies so far

res.writeHead(302, { 'Set-Cookie': 'session='+sessionID });
  • Please Note that I ask how you edit those cookies on specific routes, and not how they work
Ionut Eugen
  • 481
  • 2
  • 6
  • 27

2 Answers2

2

What you're looking for is the Path directive.

Set-Cookie: <nome-cookie>=<valor-cookie> 
Set-Cookie: <nome-cookie>=<valor-cookie>; Expires=<date>
Set-Cookie: <nome-cookie>=<valor-cookie>; Max-Age=<non-zero-digit>
Set-Cookie: <nome-cookie>=<valor-cookie>; Domain=<domain-value>
**Set-Cookie: <nome-cookie>=<valor-cookie>; Path=<path-value>**
Set-Cookie: <nome-cookie>=<valor-cookie>; Secure
Set-Cookie: <nome-cookie>=<valor-cookie>; HttpOnly

Set-Cookie: <nome-cookie>=<valor-cookie>; SameSite=Strict
Set-Cookie: <nome-cookie>=<valor-cookie>; SameSite=Lax

In your case:

Set-Cookie: Path=/something;

Further reading: HTTP cookies

Nick
  • 729
  • 8
  • 18
1

The following is a simple nodejs http server setup to read, set and delete cookie

const http = require("http");

const PORT = process.env.PORT || 3003;

const setCookie = (res, name, value, opts) => {
    let str = name + "=" + value;

    if(opts){
        if(opts.expires){
            str += "; Expires=" + opts.expires.toUTCString();
        }
    }

    res.writeHead(200, {
        "Set-Cookie": str
    });
}

const routes = [
    {
        method: "GET",
        path: "/",
        callback: (req, res) => {
            return "hello at /";
        }
    },
    {
        method: "GET",
        path: "/set-cookie",
        callback: (req, res) => {
            setCookie(res, "mycookie", "test")
            return "Cookie set `mycookie` with value `test`";
        }
    },
    {
        method: "GET",
        path: "/get-cookie",
        callback: (req, res) => {
            return JSON.stringify(parseCookies(req));
        }
    },
    {
        method: "GET",
        path: "/delete-cookie",
        callback: (req, res) => {
            return setCookie(res, "mycookie", "test", {expires: new Date(0)});
        }
    }
];

const parseCookies = (req) => {
    const list = {};
    const cookie = req.headers.cookie;

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

    return list;
}

const routeMatches = (original, requested) => {
    return original === requested; // basic string match without any pattern checking etc...
}

const handleRoute = (req, res) => {
    const _path = req.url;
    const _method = req.method;

    for(let i = 0; i < routes.length; i++){

        const route = routes[i];

        if(route.method === _method && routeMatches(route.path, _path)){
            return route.callback(req, res);
        }
    }
    return "404, Not Found " + _path;
};

const handleRequest = (req, res) => {
    const response = handleRoute(req, res);
    res.end(response);
};

const server = http.createServer(handleRequest);

server.listen(PORT, () => {
    console.log("Server running at http://localhost:%s", PORT);
});

handleRequest handles all of the requests passed down to this basic server.

handleRoute method is a very simple parser. This function basically take all the incoming requests to the server and matches the url with the registered routes on the routes array defined above and return response by invoking the callback method.

There are three other helper methods: setCookie to set the cookie in the response header, parseCookie to parse the raw cookies from the request header in a key value pair and routeMatches to check if the provided paths matches.

/set-cookie path would simply set a cookie in the header /get-cookie path would get the list of cookies /delete-cookie path would delete the cookie set in the /set-cookie path

A quick note, You can't really delete a cookie, you can set the expire time to a previous time than now which will remove the cookie from the jar.

Hope this helps.

maksbd19
  • 3,785
  • 28
  • 37