Learn

So far, we have a middleware set up to instantiate sessions and store session data server-side. We should make use of client-side storage so that the user’s browser can automatically send over the session identifier with each incoming HTTP request.

In this exercise, we’ll tell the client browser to create a cookie that stores the session ID. We will also modify cookie attributes to add a bit of security. We can add a cookie property in our session middleware like so:

app.use( session({ secret: "f4z4gs$Gcg", cookie: { maxAge: 1000 * 60 *60 * 24, secure: true, sameSite: "none" }, saveUninitialized: false, resave: false, }) );

Cookies will have a few default properties set, but we can specify them using key-value pairs. The maxAge property sets the number of milliseconds until the cookie expires. In this case, we’re setting it to expire in 24 hours. We’re also providing it with the secure attribute so it’s only sent to the server via HTTPS. Lastly, we’re adding a sameSite property and setting it to "none" in order to allow a cross-site cookie through different browsers.

Other cookie properties include:

  • cookie.expires
  • cookie.httpOnly
  • cookie.sameSite

Instructions

1.

A session has been provided for you, but it’s missing the cookie property. Add a cookie and give it the following attributes:

  • A property to expire the cookie in 48 hours (172800000 milliseconds).

  • A property to ensure that cookies are only sent through HTTPS requests.

  • A property to ensure that cookes work cross-site.

Type node app.js into the Terminal to start the node app.

Press the Check Work button to check your work for each checkpoint.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?