question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cookie is set on localhost on every request but not in production

See original GitHub issue

Problem

When I run my next application locally Set-cookie is set on every request as expected (I am using nextjs-auth0 for authentication https://github.com/auth0/nextjs-auth0). But after deploying my app to AWS this is missing. Set-cookie is only set when I initially login to my application on the /api/auth/callback path.

Setup

I have my api deployed with serverless.com on AWS Api Gateway as Lambda@Edge. My next application is deployed with serverless-next.js. In my next application I have this [...path].ts file to proxy all requests to that api:

import { getAccessToken, withApiAuthRequired } from "@auth0/nextjs-auth0";
import { createProxyMiddleware } from "http-proxy-middleware";
import { Request, Response } from "http-proxy-middleware/dist/types";
import { NextApiHandler } from "next";

const { AUTH0_AUDIENCE: apiURL } = process.env;
const proxy = createProxyMiddleware({
    changeOrigin: true,
    pathRewrite: {
        "^/api": "",
    },
    target: apiURL,
});

const handler: NextApiHandler = withApiAuthRequired(async (req, res) => {
    try {
        const { accessToken } = await getAccessToken(req, res);
        if (accessToken) {
            req.headers["content-type"] = "application/json";
            req.headers["authorization"] = `Bearer ${accessToken}`;
        } else {
            return res.status(403).json({
                message: "No access token",
            });
        }
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        return proxy(req as unknown as Request, res as unknown as Response, () => {});
    } catch {
        return res.status(403).json({
            message: "No access token",
        });
    }
});

export default handler;

export const config = {
    api: {
        bodyParser: false,
    },
};

Situation

Locally everything works fine and I get these response headers on every request:

access-control-allow-credentials: true
access-control-allow-methods: *
access-control-allow-origin: *
connection: close
content-encoding: gzip
content-length: 1424
content-type: application/json
date: Sat, 22 Jan 2022 05:10:45 GMT
referrer-policy: no-referrer
Set-Cookie: appSession=XXX; Path=/; Expires=Sun, 23 Jan 2022 05:10:45 GMT; HttpOnly; SameSite=Lax
strict-transport-security: max-age=15552000; includeSubDomains; preload
via: 1.1 edd6d90087c4f2b49e182778a2273adc.cloudfront.net (CloudFront)
x-amz-apigw-id: MVO4_FX3FiAFg-w=
x-amz-cf-id: LnCgjm45aQUCX4-9xpPMS_v3bvcvFevWNx4xHdMli6uzQzlMN8KO6A==
x-amz-cf-pop: AMS54-C1
x-amzn-requestid: 6a859b31-9277-473f-a5a8-e68914f5e5d0
x-amzn-trace-id: Root=1-61eb91d2-3e44d6515e9d1d12592e07f7;Sampled=0
x-cache: Miss from cloudfront
x-content-type-options: nosniff
x-dns-prefetch-control: off
x-download-options: noopen
x-permitted-cross-domain-policies: none

On production however the same requests look like this with Set-cookie missing:

access-control-allow-credentials: true
access-control-allow-methods: *
access-control-allow-origin: *
content-encoding: gzip
content-length: 1424
content-type: application/json
date: Sat, 22 Jan 2022 05:23:13 GMT
referrer-policy: no-referrer
server: CloudFront
strict-transport-security: max-age=15552000; includeSubDomains; preload
via: 1.1 4d0f1cf23ad7680cffcd37454ed8e57c.cloudfront.net (CloudFront)
x-amz-apigw-id: MVQuQHm3liAFbVw=
x-amz-cf-id: a_ZqJCDWWDLQVpK46AjVp6SF9CYKpAtkkGdDBieprl6w3IHgPGa4sQ==
x-amz-cf-pop: AMS50-C1
x-cache: LambdaGeneratedResponse from cloudfront
x-content-type-options: nosniff
x-dns-prefetch-control: off
x-download-options: noopen
x-permitted-cross-domain-policies: none

The differences between local and production are:

  • Set-cookie is missing
  • x-amzn-requestid is missing
  • x-amzn-trace-id is missing
  • x-cache is LambdaGeneratedResponse from cloudfront instead of Miss from cloudfront

Can someone help me out? I am trying to figure this out for days now

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:10 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
albehrenscommented, May 19, 2022

@ShawnFumo Yes, I would not recommend this for production or business critical applications. I am using this for my pet projects. Please let me know if you found a solution though 😃

0reactions
ShawnFumocommented, May 24, 2022

@albehrens In theory you’d grab the if/else block and stick it right before the return proxy part (leaving out the res.send). There’s a chance it won’t work for you since I’m not sure if the headers being locked down will freak out the proxy middleware you’re using. If it doesn’t work, I’m planning to submit a PR soon with a change to withApiAuthRequired that’d work without you having to change the original code. No guarantee they’ll accept it, but hoping to do it similar to another change they did recently.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Cookies are set in local but not in production - Stack Overflow
I'm using React + Next js on the frontend, Node.JS Express on the backend. While working on localhost, I was able to set...
Read more >
How to Send Cookies from Express to a Front-End Application ...
How to send cookies from an Express app via express-session package to the frontend in an HTTPS protocol.
Read more >
Cross-Site Cookies Will Now Be Rejected on localhost ...
The new rule demands that all cross-site cookies set in a browser have to be set with Secure attribute if they are to...
Read more >
Options | NextAuth.js
When deploying to production, set the NEXTAUTH_URL environment variable ... By default NextAuth.js does not include an adapter any longer.
Read more >
Cookie not being set in react app (express backend) - Reddit
Localhost is a secure context and so is allowed access to things that normally require HTTPS, including secure cookies: Secure Optional.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found