DEV Community

Cover image for Cookies in Javascript
Ifeanyi Chima
Ifeanyi Chima

Posted on • Updated on

Cookies in Javascript

A cookie is a tiny amount of information that gets sent between a server-side and a client-side. A web browser stores this information at the time of browsing. A cookie contains the information as a string generally in the form of a name-value pair separated by colons reference

If they are not on the same domain, cookies will not get sent because cookies can not cross domains, that is what makes them secure.

During development,

> server is at localhost: 3500

> front-end web app is at localhost: 3000

They are considered different hosts by CORS. Therefore all requests to the server are covered by CORS security rules.

BMC

Front-end

fetch in Javascript
If you are using the native fetch in javascript, {Credentials: include} is an option you can use to send cookies to the server.

Axios
In axios, {withCredentials: true} is an option you can set to include cookies to send to the server.

Back-end

res.header("Access-Control-Allow-Credentials", true)
Enter fullscreen mode Exit fullscreen mode

You should set this header on the servers' response, this header works in conjunction with the options you set on the front-end.

This tells the browser to expose the servers' response to the front-end javascript code If the request was made with credentials. what are credentials ?, Credentials are cookies, authorization headers e.t.c

So, if a request was made for a resource to the server with credentials included, and if this header is not returned with the resource, the servers' response is ignored by the web browser and not returned to the web content.

Creating a cookie

Our primary language is Node.js, so to create a cookie in Node.js

const myCountry = "Antarctica"

// saving information in a cookie
res.cookie('jwt', myCountry, { httpOnly: true, sameSite: "None", secure: true, maxAge: 24 * 60 * 60 * 1000 });
Enter fullscreen mode Exit fullscreen mode

jwt, this is the name of the cookie
myCountry, this is the information to store in the cookie

Options
We can pass in options to describe additional information about the cookie

httpOnly: true, this makes the cookie not accessible by javascript, which prevents a malicious actor from getting a hold of it.
sameSite: "None", this makes the cookie work across site.
secure: true, this makes the cookie work in a secure connection example "https" in browsers.
maxAge: 24 * 60 * 60 * 1000, is the expiration set for the cookie, this cookie has been set to expire in one day.

Front-end
To access a cookie on the front-end (web browser), open your browser console CTRL+SHIFT+I and type in.

document.cookie

our cookie is httpOnly, so you will not see it.

Thank You, Please follow me

linkedin.com/in/ifeanyi-thankgod-chima/
https://twitter.com/ifeanyiTchima

Buy Me A Coffee

Top comments (0)