No Cookies with Rails API, CORS and Next getInitialProps

342 Views Asked by At

I have a Rails API only backend with rack-cors installed at port 3000. My NextJS is running on port 5000.

My goal is to consume a cookie set by the server within my NextJS app. It contains a JWT token which holds an email and roles, which will be decoded and used for Authorization.

  • With Postman I can see the Cookie.
  • I have set my Cookie in Rails with httpOnly, but I can't see it my Chrome-dev-tools.
  • When I set a httpOnly cookie with NextJS, it's present.
  • I can see it in the DevTools "response" when POST to Rails's /login but not in the Application -> Storage -> Cookies(see images attached).

It seems Chrome does not set the cookie in DevTools "storage", it's always empty. Equally if I use "httpOnly" or not.

Can someone help me to consume the Cookie on NextJS (client side)?

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'localhost:5000', '127.0.0.1:5000'

    resource '*',
             headers: :any,
             methods: [:get, :post, :put, :patch, :delete, :options, :head],
             expose: ['Per-Page', 'Total', 'Link', 'ETag', 'Set-Cookie']

end

Here I set my cookie in the Rails controller:

    response.set_cookie(
      "withIP",
      {
        value: auth_token[:token],
        expires: 30.minutes.from_now,
        path: "/",
        domain: "localhost:5000", # tried to remove domain completly also tried "127.0.0.1" as domain, as well as '.localhost'
        secure: Rails.env.production?,
        httponly: true # Rails.env.production?
      }
    )

This is my request in the NextJS app:

        return fetch(`${PublicApiUrl}/auth/login.json?${qs.stringify(options)}`,
            { method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            credentials: 'same-origin', // also tried 'credentials' and with 'inline', as well completely removed at all.
        })
            .then((response) => {
                console.log("RESPONSE", response); // 1* see image below
                console.log("RESPONSE HEADERS", response.headers); //  *2 ALWAYS undefined
                console.log("RESPONSE forEeach", response.headers.forEach(console.log)); // ALWAYS undefined
                

                console.log("response.headers.get('set-cookie')", response.headers.get('set-cookie')); // NULL
                console.log("document.cookie", document.cookie); // nope
                return response.json()
                } )
            .then((data)=>{
                console.log("DATA", data); // returns my authToken
                return data;
            })

*1 console.log from above

RESPONSE 
Response {type: 'cors', url: 'http://localhost:3000/auth/login.json?email=xxxxxxx&password=xxxxxx', redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: true
headers: Headers
[[Prototype]]: Headers
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3000/auth/login.json?email=XXXXXX&password=XXXXXX"

*2 RESPONSE HEADERS (console.log from above)

RESPONSE HEADERS Headers {}[[Prototype]]: Headers

Storage -> Cookie missing

Request Response Chrome dev tools

0

There are 0 best solutions below