Stretch0
Stretch0

Reputation: 9251

How to set a same domain cookie with Heroku subdomains?

I have my front end running on one Heroku instance: fe.herokuapp.com

And my back end running on another instance: be.herokuapp.com

I want to set a same domain cookie when a user logs in from the front end.

I am using Koa cookies module to set the cookie like so:

cookies.set("accessToken", token, {
  maxAge: 1000 * 60 * 24,
  signed: true,
  secure: process.env.NODE_ENV === "production",
  httpOnly: true,
  domain: process.env.ORIGIN_HOSTNAME || "localhost"
})

If it helps, I'm using a React front end and a Node back end (using Koa).

Via Postman, my back end returns the following set-cookie header:

accessToken=<access_token>; path=/; expires=Sun, 01 Sep 2019 16:27:24 GMT; domain=.herokuapp.com; secure; httponly

However, via my React app, I can't see any set-cookie headers.

My front end is using isomorphic-unfetch library with credentials = "include". (perhaps this needs to be same-origin since it's on the same subdomain?)

My two questions are:

  1. Why can't I set the domain value in my cookie from the back end to be fe.herokuapp.com?
  2. Why can I see the set-cookie header via postman but not in my front end React app?

Happy to post more code snippets if need be.

Upvotes: 4

Views: 841

Answers (2)

itsTanany
itsTanany

Reputation: 457

herokuapp.app is listed in Public suffix List which means cookies are blocked from bein set to the domain "herokuapp.com"

you must use custom domain technique

Upvotes: 2

Vlad Pavlovski
Vlad Pavlovski

Reputation: 2010

Stuck with this issue for some time. What I figured out:

  1. Need add proxy attribute to app:
const app = new Koa()
app.proxy = true
  1. Extend cookies options with sameSite attribute:
cookies.set("accessToken", token, {
  maxAge: 1000 * 60 * 24,
  signed: true,
  secure: process.env.NODE_ENV === "production",
  httpOnly: true,
  domain: process.env.ORIGIN_HOSTNAME || "localhost",
  sameSite: 'none' // <-- add this
})

Before that I bought a domain for my app. Frontend app point to "domain.com", and Backend app point to "api.domain.com". But now I am not sure if it was necessary.

Upvotes: 0

Related Questions