How to transfer HTTP Only Cookies with express back-end and the Fetch API 🔥

Георги Пеев
2 min readSep 11, 2019

The first thing when we are building a REST Application is to create somehow authorization and authentication in it. 🔑

So suppose we are using some form of authentication ,like JWT ,which token MUST be stored in the client’s cookies with flag HTTP Only ,so it can’t be accessed from scripts (XSS).🐱‍💻

Lets get to the point how to transfer HTTP Only Cookies via Express Back-End and requests made via the Fetch API.

  1. The first thing is to install the cookie-parser library,which is a middleware ,so express somehow can manage cookies:

npm install cookie-parser

2. Then go where you configure your Express application and add the cookie-parser library as a middleware:

const express = require('express');
const cookieParser = require('cookie-parser');

app.use(cookieParser());

3.Now our Express application can do all of the cookie parsing stuff for us!

4.Now suppose you have a endpoint/url , our will be http://localhost:9999/example and when we create a request with the Fetch API to the endpoint ,our client automatically to receive a Cookie 🍪

5.Now in our Express application`s endpoint /example set a cookie to be returned:

response.cookie('JWT', '1234', {
maxAge: 86_400_000,
httpOnly: true
});
response.render('<h1>Cookie has been send with the response</h1>');

6.So when we access the route ,lets say directly via the browser this cookie will be set automatically.

A cook has been set after we visited http://localhost:9999

7.This is perfect ,we have a cookie after visiting this route and it is HttpOnly,but the main reason this guide to exist is how we will do it if we use the Fetch API?

8.The first thing is allow our Express application to be able to receive requests from the host on which the Fetch API makes the calls in our situation it makes them from http://localhost:8000:

const express = require('express');
const cors = require('cors');

app.use(cors({
origin: 'http://localhost:8000',
credentials: true
}));

9.The last thing is to create a fetch request via the Fetch API from http://localhost:8000 to http://localhost:9999/example:

fetch('http://localhost:9999/example',{
method: ‘GET’,
credentials: 'include'
});

And now no matter that we made the request from another host ,we receive the cookies 🤗

NOTE:The credentials include is required ,otherwise fetch can’t set cookies.

--

--