Secure API Authentication with NextJs: HTTP Only Cookie

Jake Owen
2 min readNov 6, 2021

--

Securing anything on the internet is difficult. This series doesn’t ensure your application will be 100% secure from attackers, but hopefully, your application will be more secure than it was before.

We’ll be covering how to store a JWT in a cookie, and using this to call APIs in NextJs, both client-side and server-side. If you’d like to know more about the benefit of JWTs, jwt.io, and JWTs in Node.JS have you covered.

There are three main ways to store JWT tokens. LocalStorage, SessionStorage, and Cookies.

LocalStorage: Store values in key/values pairs within the web browser with no expiration date. Accessible via browser.

SessionStorage: Similar to LocalStorage, but is only stored for the session. If the browser or tab is closed, the data is lost.

Cookies: All cookies for a domain are stored in a single string. Data persists across tabs and browser closures. Settings are available for expiry date, HTTPS specific support & whether it can be accessed via a browser.

All of the above can be vulnerable to Cross-site scripting (XSS) attacks. XSS is where the attacker attaches code to a website and steals the user's secure authentication token.

How can a token be stolen through XSS?

  1. You have a website — www.mywebsite.com.
  2. The attacker emails a link to a user, that has malicious code attached to the end of the URL. www.mywebsite.com/{maliciousCode}
  3. Malicious code accesses the user's JWT token and sends the token to the attacker. The attacker can now access your APIs impersonating the user the token was taken from.

How can we prevent XSS?

Cookies have an option, Http-Only. This prevents them from being accessed in the browser, and will only be sent in API calls from your application. This is the predominant way you can safeguard your website from XSS attacks.

Cookies have another option (usually for production), Secure - which means the cookie is only sent in an API request if it https. The secure flag cannot be set if the site is insecure (http)

This series will show how you can send HTTP-only cookies from an API; how to set up your environment to consume them and send them in both your client-side & server-side API requests.

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

--

--