Skip to content

Error using getPayloadSession() after deploying to Vercel #33

Closed
@EzeLamar

Description

@EzeLamar

Plugin version

0.8.0

Payload version

3.33.0

Auth.js version

5.0.0-beta.25

Describe the bug

After deploying the project to Vercel, pages that use getPayloadSession() fail to load successfully, and the following error is shown:

Error: Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers

After some investigation, I found the root of the problem lies in the implementation of payload-authjs/dist/payload/session/getPayloadSession.js, specifically the usage of headers() from next/headers.

In this implementation, headers() is passed directly to the fetch call. However, headers() returns a read-only Headers object tied to the incoming request context, and it is not guaranteed to be compatible with fetch. This can result in missing cookie or authorization headers during the request, especially in edge environments like Vercel.

✅ Proposed Solution
A more reliable approach is to explicitly extract the necessary headers (e.g., cookie and authorization) and create a new Headers object to pass to fetch, as shown below:

const requestHeaders = await headers();

const fetchHeaders = new Headers();
const authHeader = requestHeaders.get("authorization");
const cookieHeader = requestHeaders.get("cookie");

if (authHeader) fetchHeaders.append("authorization", authHeader);
if (cookieHeader) fetchHeaders.append("cookie", cookieHeader);

const response = await fetch(`${serverUrl}/api/${userCollectionSlug}/me`, {
  headers: fetchHeaders,
  cache: "force-cache",
  next: {
    tags: ["payload-session"],
  },
});

I've tested this solution on Vercel and it appears to resolve the issue.

Hope this helps fix the problem!

To Reproduce

  1. build a project using getPayloadSession() and deploy to Vercel.
  2. Check the Vercel logs console.

Additional context / Screenshots

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingstatus: verifiedIf an issue has been reproduced

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions