Dec 18, 2024 · 3 min read

Get that damn setting httponly cookie to work

Frustrated why the browser keeps ignoring your Set-Cookie header resulting in no httponly cookie being set? I’d wasted a whole day on it to present you the remedy here. Read on!


If you’re trying to set httponly cookie from the back-end response (using Set-Cookie header) and you don’t see the cookie appearing in your browser’s dev tools, that’s because some settings are missing on either front-end or back-end. I’ve listed all necessary settings below so let’s try comparing and see what you’ve missed 👇

It isn’t so straightforward to get this bad boy to show up as it might seem.
It isn’t so straightforward to get this bad boy to show up as it might seem.

Max-Age and Path is properly set

Might be the most trivial one, but make sure that you set Max-Age long enough so that it doesn’t vanish before you have a chance to see it, and the URL you’re visiting in the browser contains the path specified when you created the cookie.

CORS Allow Origins is set to allow your front-end domain

Wildcard (*) won’t cut it here. Make sure it’s properly set using your front-end domain string value. For example if you’re running a front-end on your localhost address at http://localhost:3000, it should be set as one of the allowed origins.

CORS Allow Methods is properly set to supposed values

No matter whether it’s POST/GET/PUT/PATCH… make sure whatever HTTP methods you’re using are allowed in your CORS settings.

CORS Allow Credentials is set to true

Without this, the cookie set in the response header won’t be saved in the browser.

So far I’ve listed all CORS related attributes that you need to get them right. Here’s a sample code written in Go to do that:

	e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins:     []string{"http://localhost:3000"},
		AllowMethods:     []string{echo.GET, echo.POST, echo.PUT, echo.DELETE, echo.PATCH},
		AllowCredentials: true,
	}))

Credentials are included in front-end requests

For example, if you’re using Next.js fetch then the request option should include credentials: 'include' , or if you are using axios then the request option should have { withCredentials: true } included.

If you are using Next.js, your page sending requests written in Server Component or Client Component might make a difference

If your page is written in Server Component communicating with the back-end and it’s receiving response that sets httponly cookie, you need to do some additional work to set the httponly cookie again during server-side rendering logic, or else whatever cookie set by the back-end that the Server Component is receiving would be discarded.

If your page is written in Client Component then you don’t need to do anything, the cookie set by the back-end would get saved automatically by the browser.

Hope this helps you if you’re frustrated with trying to set cookie server-side. I’m with you 🫂