Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error while setting up the middleware - withAuth / getToken #5105

Closed
dawidseipold opened this issue Aug 6, 2022 · 8 comments
Closed

Error while setting up the middleware - withAuth / getToken #5105

dawidseipold opened this issue Aug 6, 2022 · 8 comments
Labels
incomplete Insufficient reproduction. Without more info, we won't take further actions/provide help. middleware Related to middleware stale Did not receive any activity for 60 days

Comments

@dawidseipold
Copy link

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 dawidseipold added the triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. label Aug 6, 2022
@balazsorban44
Copy link
Member

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
Copy link
Member

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

@dawidseipold dawidseipold changed the title Error while setting up the middle - withAuth / getToken Error while setting up the middleware - withAuth / getToken Aug 9, 2022
@ThangHuuVu ThangHuuVu added incomplete Insufficient reproduction. Without more info, we won't take further actions/provide help. middleware Related to middleware and removed triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. labels Aug 21, 2022
@stale
Copy link

stale bot commented Oct 21, 2022

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 stale bot added the stale Did not receive any activity for 60 days label Oct 21, 2022
@stale
Copy link

stale bot commented Oct 28, 2022

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 stale bot closed this as completed Oct 28, 2022
@Shreyas-29
Copy link

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.

@anishbishnoi127
Copy link

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

@success-glich
Copy link

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.

@01herve
Copy link

01herve commented Jan 25, 2024

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: ["/"]}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
incomplete Insufficient reproduction. Without more info, we won't take further actions/provide help. middleware Related to middleware stale Did not receive any activity for 60 days
Projects
None yet
Development

No branches or pull requests

7 participants