Skip to main content

Cookies

Cookies are small pieces of data that a website sends to a user's web browser while the user is browsing that website. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user's previous activity.

Benefits

Cookies serve several primary purposes:

  1. Session Management: Cookies are often used to handle user sessions. For example, when you log into a website, a cookie is set to remember your login state. So, as you navigate the site, you remain logged in.

  2. Personalization: Cookies can store user preferences to personalize the user's experience on the site. For example, cookies might store information about the user's preferred language, theme, or other settings.

  3. Tracking: Some cookies track user behavior on the site over time. These are often used by third-party analytics tools to understand user behavior and optimize the site accordingly. Advertisers also use tracking cookies to display targeted ads based on user activity.

  4. Security: Cookies can be used to support secure website functions. For example, a cookie can be used to remember that a user has authenticated to a site so that the server knows the user has already provided valid login credentials.

It's also important to note that there are different types of cookies - session cookies, which expire when the browser session ends, and persistent cookies, which remain on the user's device for a set period of time or until they are explicitly deleted.

USING COOKIES FOR TRACKING

Keep in mind that the use of cookies, especially for tracking and personalization, has raised privacy concerns, leading to regulations such as GDPR in Europe and CCPA in California that require sites to disclose their cookie usage and obtain user consent.

When to use

Deciding when to use cookie-parser largely depends on your application's needs. If your web application requires state management and you've chosen to do that via cookies, cookie-parser can make your life easier and your application more secure with signed cookies.

However, if your website has heavy traffic, the overhead might become a concern. If your architecture is based around stateless services (common in microservices architectures), you might want to avoid cookies and opt for other methods of maintaining state, like JWTs (JSON Web Tokens).

info

In case you're dealing with a high traffic website, consider alternatives like sessions stored in a database, JWTs, or tokens stored in HTTP headers. Also, using a load balancer to distribute traffic and session store modules to maintain session data across multiple servers can help to manage high traffic and stateful data.

The best approach often involves combining multiple techniques, tailored to your application's specific needs. Testing and monitoring your application under realistic conditions can help guide your decision-making process.

Install

Install the npm cookie-parser middleware and type definition.

npm i cookie-parser
npm i -D @types/cookie-parser

Setup

Add the cookie-parser middleware to your application using the out-of-the-box ExpressoTS middleware system.

@provide(App)
export class App extends AppExpress {
private middleware: IMiddleware;
private provider: IProvider;

constructor() {
super();
this.middleware = container.get<IMiddleware>(Middleware);
this.provider = container.get<IProvider>(Provider);
}

protected configureServices(): void {
this.middleware.addCookieParser();
}
}

Usage example

Once the middleware is added to the application, it will parse cookies from the request and make them available in the request object. The middleware can be configured with various options to control the behavior of cookie parsing.

@Get("get-cookie", cookieParser())
getCookie(){};

Let's create a route that set's a cookie with a random UUID as value, that expires in 1 hour and is only accessible via HTTP:

@httpGet("set-cookie")
setCookie(@response() res: Response) {
res.cookie("authToken", randomUUID(), {
maxAge: 60 * 60 * 1000, // 1 hour
httpOnly: true,
});
return res.send("Cookie set!");
}

Using cookies decorator

Using the @cookies() decorator, you can get all cookies from the request and use them in your route:

Create a route that gets the cookie and returns the value
@httpGet("get-cookie")
getCookie(@cookies() cookieInfo: string, @response() res: Response) {
return res.send(`Your token: ${cookieInfo["authToken"]}`);
}
tip

@cookies() decorator it is a helper to get all cookies from the request. You can also use @cookies('cookieName') to get a specific cookie.


Support us ❤️

ExpressoTS is an MIT-licensed open source project. It's an independent project with ongoing development made possible thanks to your support. If you'd like to help, please read our support guide.