next-auth icon indicating copy to clipboard operation
next-auth copied to clipboard

Error while setting up the middleware - withAuth / getToken

Open dawidseipold opened this issue 3 years ago • 2 comments

Environment

System: OS: Windows 10 10.0.22000 CPU: (4) x64 Intel(R) Core(TM) i5-6600K CPU @ 3.50GHz Memory: 17.66 GB / 31.91 GB Binaries: Node: 16.13.2 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.17 - ~\AppData\Roaming\npm\yarn.CMD npm: 8.1.2 - C:\Program Files\nodejs\npm.CMD Browsers: Edge: Spartan (44.22000.120.0) Internet Explorer: 11.0.22000.120 npmPackages: next: latest => 12.2.3 next-auth: ^4.10.3 => 4.10.3 react: 18.1.0 => 18.1.0

Reproduction URL

https://github.com/dawidseipold/melsea

Describe the issue

Hi! I have a problem with setting up the middleware for the next-auth.

No matter what I put inside of the withAuth function, I get the same error whenever I go to a configured matching route.

Server error
There is a problem with the server configuration.
Check the server logs for more information.

GET http://localhost:3000/api/auth/error?error=Configuration 500 (Internal Server Error)

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

export default withAuth({
  callbacks: {
    authorized: async ({ req, token }) => {
      const pathname = req.nextUrl.pathname;

      if (token) return true;

      return false;
    },
  },
  pages: {
    signIn: '/login',
  },
});

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

The code above is just an example of what I've tried, but the same error occurs even if I do it like this:

export { default } from "next-auth/middleware"

Throughout the whole app I retrieve the token with a getSession function, which cannot be used in the middleware. From what I read you can use getToken function as an alternative, however that also doesn't work for me, as I get the same error as described here, when I use this code:

import { getToken } from 'next-auth/jwt';
import { NextResponse } from 'next/server';

export default async function middleware(req) {
  const token = await getToken({ req, secret: process.env.JWT_SECRET });
  const { pathname, origin } = req.nextUrl;

  if (pathname.includes('api/auth') || token) {
    return NextResponse.next();
  }

  if (!token && pathname !== '/login') {
    return NextResponse.redirect(`${origin}/login`);
  }
}

All of that makes me believe that I might've setup something wrong inside of the [...nextauth].ts file, but can't really point it out myself. My guess is that I', probably juggling around between jwt and database session strategy, which would explain the lack of the token (I might be wrong though).

[...nextauth].ts

import NextAuth, { Session, User } from 'next-auth';
import SpotifyProvider from 'next-auth/providers/spotify';
import { SPOTIFY_LOGIN_URL } from '../../../lib/spotify';

export default NextAuth({
  providers: [
    SpotifyProvider({
      clientId: process.env.SPOTIFY_CLIENT_ID as string,
      clientSecret: process.env.SPOTIFY_CLIENT_SECRET as string,
      authorization: SPOTIFY_LOGIN_URL,
    }),
  ],
  secret: process.env.JWT_SECRET,
  session: { strategy: 'jwt' },
  pages: {
    signIn: '/login',
  },
  callbacks: {
    async jwt({ token, account, user }) {
      if (account && user) {
        token.accessToken = account.refresh_token;
      }
      return token;
    },

    async session(session, user) {
      session.user = user;
      return session;
    },
  },
});

How to reproduce

  1. Set up the [...nextauth].ts as above
  2. Set up middleware.ts as above

Expected behavior

If the user is not authorized by Spotify they should be redirected by middleware into '/login' route. If they are however, they should be able to use the other routes.

dawidseipold avatar Aug 06 '22 08:08 dawidseipold

Since you are using Middleware, I assume you forgot to set NEXTAUTH_SECRET: https://next-auth.js.org/configuration/options#nextauth_secret. At least I can see you set secret in ...nextauth, but nothing in Middleware.

The logs should give you more details about the configuration error.

balazsorban44 avatar Aug 08 '22 07:08 balazsorban44

Also, keep in mind that Next.js currently has an upstream bug in 12.2.3 and upwards which prevents NextAuth.js's Middleware from working properly. Tracked here: #5008

balazsorban44 avatar Aug 08 '22 07:08 balazsorban44

It looks like this issue did not receive any activity for 60 days. It will be closed in 7 days if no further activity occurs. If you think your issue is still relevant, commenting will keep it open. Thanks!

stale[bot] avatar Oct 21 '22 08:10 stale[bot]

To keep things tidy, we are closing this issue for now. If you think your issue is still relevant, leave a comment and we might reopen it. Thanks!

stale[bot] avatar Oct 28 '22 21:10 stale[bot]

I am also get the same error:

Server error

There is a problem with the server configuration.

`export { default } from 'next-auth/middleware';

// If the user is not siggned in it will go direct '/auth/signin' export const config = { matcher: ["/"] };`

I want to redirect the user to signin page if he is not signed in. Please help me to resolve the error.

Shreyas-29 avatar Feb 06 '23 18:02 Shreyas-29

same issue with me how to fix this ? http://localhost:3000/api/auth/error?error=Configuration having this issue.

anishbishnoi127 avatar Nov 17 '23 10:11 anishbishnoi127

I have the same issues, how could I fix this? as it should redirect to api/aut/signin

http://localhost:3000/api/auth/error?error=Configuration having this issue.

success-glich avatar Dec 28 '23 08:12 success-glich

this is a solution import { withAuth } from "next-auth/middleware"

export default withAuth( function middleware(req) { console.log('req: ', req); console.log(req.nextauth.token) },

)

export const config = { matcher: ["/"]}

01herve avatar Jan 25 '24 21:01 01herve