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.