nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.16k stars 3.35k forks source link

Getting "Error: Cannot find module 'next/headers'" on building the app #6559

Closed nike1v closed 1 year ago

nike1v commented 1 year ago

Question 💬

I have updated the next-auth to the latext version (4.19.0) and still get this error when tying to build the app with next 12. I have tried to use this when the next-auth version was 4.16.0 and I saw this issue for the first time. I saw the issue here that it should be fixed, but I assume that it is not and to use next-auth 4.16+ I should use next13, am I right? Hope on your help.

How to reproduce ☕️

run - npm install next-auth@latest next@12.x.x and try to build the application

Contributing 🙌🏽

No, I am afraid I cannot help regarding this

github-actions[bot] commented 1 year ago

We cannot recreate the issue with the provided information. Please add a reproduction in order for us to be able to investigate.

Why was this issue marked with the incomplete label?

To be able to investigate, we need access to a reproduction to identify what triggered the issue. We prefer a link to a public GitHub repository (template), but you can also use a tool like CodeSandbox or StackBlitz.

To make sure the issue is resolved as quickly as possible, please make sure that the reproduction is as minimal as possible. This means that you should remove unnecessary code, files, and dependencies that do not contribute to the issue.

Please test your reproduction against the latest version of NextAuth.js (next-auth@latest) to make sure your issue has not already been fixed.

I added a link, why was it still marked?

Ensure the link is pointing to a codebase that is accessible (e.g. not a private repository). "example.com", "n/a", "will add later", etc. are not acceptable links -- we need to see a public codebase. See the above section for accepted links.

What happens if I don't provide a sufficient minimal reproduction?

Issues with the incomplete label that receives no meaningful activity (e.g. new comments with a reproduction link) are automatically closed and locked after 30 days.

If your issue has not been resolved in that time and it has been closed/locked, please open a new issue with the required reproduction.

I did not open this issue, but it is relevant to me, what can I do to help?

Anyone experiencing the same issue is welcome to provide a minimal reproduction following the above steps. Furthermore, you can upvote the issue using the :+1: reaction on the topmost comment (please do not comment "I have the same issue" without repro steps). Then, we can sort issues by votes to prioritize.

I think my reproduction is good enough, why aren't you looking into it quicker?

We look into every NextAuth.js issue and constantly monitor open issues for new comments.

However, sometimes we might miss one or two. We apologize, and kindly ask you to refrain from tagging core maintainers, as that will usually not result in increased priority.

Upvoting issues to show your interest will help us prioritize and address them as quickly as possible. That said, every issue is important to us, and if an issue gets closed by accident, we encourage you to open a new one linking to the old issue and we will look into it.

Useful Resources

balazsorban44 commented 1 year ago

FWIW, this is a duplicate of #5743, but it seems like multiple people are reporting issues, so I'll leave this open until someone gives us a reproduction.

The most likely scenario is that you might have forgotten to pass req and res, which is required in all contexts, except app dir, which is a Next.js 13 feature only.

It's documented as such for:

Only the app directory allows no or 1 param being passed: https://next-auth.js.org/configuration/nextjs#in-app-directory

AliHoussein commented 1 year ago

I have the same issue and seem to have pinpointed the culprit in my case. It seems the middleware does not work properly.

package.json

    "jsonwebtoken": "^9.0.0",
    "next": "^12.3.4",
    "next-auth": "^4.19.0",

I use a custom encode/decode functions in [...nextauth].ts

import jwt from 'jsonwebtoken';
import NextAuth, { NextAuthOptions } from 'next-auth';
import { JWTDecodeParams, JWTEncodeParams } from 'next-auth/jwt';

jwt: {
    // You can define your own encode/decode functions for signing and encryption
    async encode({ secret, token }: JWTEncodeParams): Promise<String> {
      const jwtClaims = {
        id: token?.id,
        sub: token?.sub,
        name: token?.name,
        email: token?.email,
        picture: token?.picture,
        iat: Math.floor(Date.now() / 1000),
        exp: Math.floor(Date.now() / 1000) + 24 * 60 * 60, //1 day
        'https://hasura.io/jwt/claims': {
          'x-hasura-allowed-roles': ['user'],
          'x-hasura-default-role': 'user',
          'x-hasura-role': 'user',
          'x-hasura-user-id': token?.id,
        },
      };
      const encodedToken = jwt.sign(jwtClaims, secret, { algorithm: 'HS256' });
      return encodedToken;
    },
    async decode({ secret, token }: JWTDecodeParams) {
      const decodedToken = jwt.verify(token, secret, { algorithms: ['HS256'] });
      return decodedToken as any;
    },
  },

Also have a middleware in middleware.ts

import { withAuth } from 'next-auth/middleware';

import { authOptions } from './pages/api/auth/[...nextauth]';

// More on how NextAuth.js middleware works: https://next-auth.js.org/configuration/nextjs#middleware
export default withAuth({
  jwt: { decode: authOptions.jwt?.decode },
  callbacks: {
    authorized({ req, token }) {
      console.log(req, token);
      // `/admin` requires admin role
      if (req.nextUrl.pathname === '/backoffice') {
        return token?.userRole === 'admin';
      }
      return !!token;
    },
  },
});

export const config = { matcher: ['/backoffice', '/profile'] };

If I remove export const config = { matcher: ['/admin', '/me'] }; OR try to go through a protected URL it crashes the server with the following error

error - ./node_modules/next-auth/next/index.js:90:6
Module not found: Can't resolve 'next/headers'

Import trace for requested module:
./node_modules/next-auth/index.js
./pages/api/auth/[...nextauth].ts
./middleware.ts

Also I have few type issues for decode (if I remove as any) in [...nextauth].ts

Type '({ secret, token }: JWTDecodeParams) => Promise<string | JwtPayload>' is not assignable to type '(params: JWTDecodeParams) => Awaitable<JWT>'.
  Type 'Promise<string | JwtPayload>' is not assignable to type 'Awaitable<JWT>'.
    Type 'Promise<string | JwtPayload>' is not assignable to type 'JWT'.
      Index signature for type 'string' is missing in type 'Promise<string | JwtPayload>'.

It feels also that the documentation would be more helpful if a bit more detailed:

balazsorban44 commented 1 year ago

please add a full (but minimal reproduction), preferably a public github repository, not just snippets.

mayank1513 commented 6 months ago

I am trying to deploy https://github.com/mayank1513/nextjs-themes-ultralight to Vercel.

All the examples and the library are built very well locally. However, on Vercel it throws this error - "Type error: Cannot find module 'next/headers' or its corresponding type declarations."

at ../../lib/nthul/src/server/server-target/server-target.tsx:2:25