Problems with next-auth middleware

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

const publicFileRegex = /\.(.*)$/;
const anonymousRoutes = ['/auth/signin']; // The whitelisted routes

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

// Important! The below only checks if there exists a token. The token is not validated! This means
// unauthenticated users can set a next-auth.session-token cookie and appear authorized to this
// middleware. This is not a big deal because we do validate this cookie in the backend and load
// data based off of its value. This middleware simply redirects unauthenticated users to the login
// page (and sets a callbackUrl) for all routes, except static files, api routes, Next.js internals,
// and the whitelisted anonymousRoutes above.
return Boolean(
req.cookies.get('next-auth.session-token') || // check if there's a token
pathname.startsWith('/_next') || // exclude Next.js internals
pathname.startsWith('/api') || // exclude all API routes
pathname.startsWith('/static') || // exclude static files
publicFileRegex.test(pathname) || // exclude all files in the public folder
anonymousRoutes.includes(pathname)
);
},
},
// the custom pages
pages: {
signIn: '/auth/signin',
},
});
import { withAuth } from 'next-auth/middleware';

const publicFileRegex = /\.(.*)$/;
const anonymousRoutes = ['/auth/signin']; // The whitelisted routes

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

// Important! The below only checks if there exists a token. The token is not validated! This means
// unauthenticated users can set a next-auth.session-token cookie and appear authorized to this
// middleware. This is not a big deal because we do validate this cookie in the backend and load
// data based off of its value. This middleware simply redirects unauthenticated users to the login
// page (and sets a callbackUrl) for all routes, except static files, api routes, Next.js internals,
// and the whitelisted anonymousRoutes above.
return Boolean(
req.cookies.get('next-auth.session-token') || // check if there's a token
pathname.startsWith('/_next') || // exclude Next.js internals
pathname.startsWith('/api') || // exclude all API routes
pathname.startsWith('/static') || // exclude static files
publicFileRegex.test(pathname) || // exclude all files in the public folder
anonymousRoutes.includes(pathname)
);
},
},
// the custom pages
pages: {
signIn: '/auth/signin',
},
});
I have this middleware, and it works locally, but when deployed, it does not work, the error i get is redirected you too many times.
1 Reply
vrba
vrba2y ago
I found the problem is in using sessions, not using jwt. Is there an easy way to move to jwt, without changing the app in a big way
Want results from more Discord servers?
Add your server