Setting and Using Cookies with a Node.js / Express Server

Ethan Collins
3 min readFeb 18, 2020

--

Until recently I had been taking my server’s token from a login request, and saving it to localStorage on the frontend. The security risk of this is that the token is accessible by JavaScript, and is susceptible to XSS. To get around this, we can store a token as a cookie on our front end, sent from the server with an ‘httpOnly’ flag. This means that JavaScript won’t be able to access our cookie, and is better for sensitive info than localStorage.

In this blog I’ll be setting up a server using Node.js and Express, and use it to set and receive cookies. To test requests, I’ll be using Postman, a really great tool for testing endpoints and API responses. To get started, let’s set up a basic Node.js and Express server, with a GET and POST route.

mkdir server
cd server
npm init -y
touch index.js
npm i nodemon express cookie-parser

The ‘nodemon’ package is optional, but it will restart our server automatically whenever we save a file. This is super helpful in development, where you’re frequently making changes. ‘cookie-parser’ is middleware which will allow us to read cookies on the request object for our routes.

Add a script to our package.json to use nodemon:

Inside of index.js:

Now we can start up our server using “npm start”, and we should be able to hit both of our endpoints.

POST request to ‘/login’
GET request to ‘/private’

Great! Now we’re ready to start implementing cookies. In our index.js, we need to import and use the ‘cookie-parser’ middleware we previously added. The top of our index.js file should now look like this:

Now we can access the cookies of incoming requests through ‘req.cookies’. Let’s start by making our ‘private’ route deny any requests without a cookie. We check for the existence of a cookie, if there’s none we send a 401 (unauthorized), otherwise we send them our top secret data!

If we tried this endpoint right now, we should be denied since we don’t have any cookies set.

GET request to ‘/private’ without cookies

Great! Now let’s set up our post route to ‘/login’. This route will respond to a GET request and set a cookie with the name ‘token’.

In order to set cookies in the browser, you would need to include the ‘credentials’ option with your post request, to allow the server to set cookies. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials. With postman, it handles this for us. If we hit the ‘/login’ endpoint, we should see that postman now has a cookie set, with a name of ‘token’.

Great! Now that we have our cookie set, we should be allowed to access our ‘/private’ endpoint.

Hopefully this helped someone out! I’ll be writing another (longer) blog next week about using the jsonwebtoken package to create actual tokens, set the tokens as cookies on a react frontend, and handle validation and cookie deletion!

Our final index.js file:

--

--