Secure API Authentication with NextJs: Set-Cookie from API

Jake Owen
2 min readNov 6, 2021

Secure API Authentication with NextJs Series

1. HTTP Only Cookie

2. Set-Cookie from API

3. Development Server

4. Routing Microservice to the Same Port (optional)

5. Client-Side vs Server-Side API Calls

6. Access Token vs Refresh Tokens

To return a cookie to the browser, we first need to create a JWT. The library jsonwebtoken does most of the heavy lifting for us.

We’re going to pass an accountId in the body. When we consume this token in our APIs we can retrieve the accountId. We’re also going to pass an expiry time, after this time the JWT becomes invalid. We’ll talk more about expiration time in access & refresh tokens.

Now we have a JWT, we can return this in the header of the API response. Some frameworks have support specifically for setting cookies — but to keep this article framework agnostic, we’ll be sticking to headers.

The header Set-Cookie will set the cookie in the browser when the response is received.

accessToken=${accessToken} - This is the key, value pair of our cookie. We are naming it accessToken and setting the value to the JWT we created.

HttpOnly: This sets the flag HttpOnly within the browser, the cookie, therefore, cannot be accessed from client-side javascript scripts, providing protection against XSS attacks.

Max-Age — The maximum age of the cookie in seconds. This will be set in the browser under Expires . The value set will be currentTime + maxAge .

Path — If you do not include a path, the cookie will only be set on the page that received the cookie. If the user refreshes, navigates to a new page, or closes the browser, the cookie will be removed. By setting the path to / it will persist across your whole site.

Secure — When the Secure flag is set, the cookie can only be sent from HTTPS enabled sites and to HTTPS URLs. You should set this flag within your production setup to provide further protection.

--

--