Learn

Securing Cookies

In the previous exercise, we saw how cookies can be used to steal user’s data. An express server that uses express-session to store cookies has the properties httpOnly and secure to configure how to store and send cookies. Setting httpOnly and secure to true helps mitigate the risk of client-side script accessing the protected cookie.

In order to set up a cookie in an Express server, you can use the library express-session to set up a session and configure the application with specific properties pertaining to cookies:

app.use( session({ secret: "my-secret", resave: true, saveUninitialized: true, cookie: { httpOnly: true, secure: true }, }) );

Setting Security Headers

Moreover, we can include the helmet package to edit HTTP headers. Helmet.js is a collection of 15 Node modules that interface with Express. Each module provides configuration options for securing different HTTP headers. One of them being the contentSecurityPolicy which is an added layer of security that helps to detect and mitigate certain types of attacks. Fortunately, by just including this package in your express app, 11 of these modules (including the content security policy module) will be configured automatically.

You can use helmet by adding the following line of code:

app.use(helmet());

Instructions

1.

Secure the cookie by setting the httpOnly and secure attributes to the correct values.

2.

Automatically enable a number of security headers by adding helmet to this application.

  • require the package and store it in a const named helmet.
  • Use helmet in your application.

Note: If you implement helmet properly, the mini browser may appear broken. This is because of the security headers helmet enables. While inconvenient for this exercise, this is good for real-world security!

An image of the mini browser with an error message saying it "refused to connect".

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?