Introduction
Cookies are still the most recommended way to handle authentication in web applications.
Furthermore, they can be tricks to get it right and to make it work on localhost, staging, and production with the same code.
Setting Cookies
Your backend needs to set the cookies after the log-in, and it also needs to remove the cookies after the log-out.
To set a cookie in the backend you can do something like this:
const domain = null;
const secure = !['development', 'test'].includes(config.NODE_ENV);
const sameSite = config.APP_ENV === 'development' ? 'Lax' : 'Strict';
const options = {
httpOnly: true,
overwrite: true,
maxAge,
secure,
domain,
signed: true,
sameSite,
};
koaContext.cookies.set(cookieName, token, options);
We are using koa to set cookies, but it can be any node framework, and the concept would be the same in other programming languages and frameworks.
Let's dive into the cookies options:
- httpOnly: specific that this cookie can't be read by JavaScript, this is a security measure and it is recommended
- overwrite: it will override existing cookie with the same name
- maxAge: it sets an expiration date for the cookie, a short expiration time is good for security
- secure: it only sends the cookies in TLS connections
- domain: specific what domain can accept this cookie
- signed: it ensures the value was not tampered
- sameSite: it defines if the cookie should send in a cross-site request.
Making cookies work on localhost
Commonly, your backend server will run in a port, like http://localhost:5001
and your frontend will run in another port http://localhost:8003
.
If a different port is interpreted as a different domain in your browser, then you can't set cookies from 5001 to 8003.
To make cookies work in localhost, we can use a proxy on the front end.
We can do this using our webpack config:
const config = {
devServer: {
proxy: {
'/graphql': `http://localhost:5001`,
},
},
}
This will proxy http://localhost:8003/graphql
requests to http://localhost:5001/graphql
, enabling cookies to work in your localhost.
To Sum Up
To provide the best DX you need to work end to end to ensure both the backend and frontend are tweaked to support the developer's workflows.
Right now cookies are so easy to use that we even forget that we migrated from local storage a few years ago.
If you are still using local storage to save your authentication tokens, I recommend you migrate to cookies.
Woovi
Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.
If you want to work with us, we are hiring!
Photo by Vyshnavi Bisani on Unsplash
Top comments (0)