-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
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
Next.js 13 - Middleware - Expected an instance of Response to be returned #5649
Comments
The same here! In my case I protect all export { default } from 'next-auth/middleware'
export const config = { matcher: ['/admin/(.*)'] } |
Also experiencing this. No issues if i remove my middleware.ts file. Code: export { default } from "next-auth/middleware";
export const config = {
matcher: ["/((?!login|api|_next|static|favicon.ico).*)"],
}; |
I meet the same issue, and I found something interesting. I used After review the source code, I found it doesn't identify the first param as instance of NextRequest: export function withAuth(...args: WithAuthArgs) {
if (!args.length || args[0] instanceof NextRequest) {
// @ts-expect-error
return handleMiddleware(...args)
}
if (typeof args[0] === "function") {
const middleware = args[0]
const options = args[1] as NextAuthMiddlewareOptions | undefined
return async (...args: Parameters<NextMiddlewareWithAuth>) =>
await handleMiddleware(args[0], options, async (token) => {
args[0].nextauth = { token }
return await middleware(...args)
})
}
const options = args[0]
return async (...args: Parameters<NextMiddleware>) =>
await handleMiddleware(args[0], options)
} Interesting, isn't it ??? I print the stack of the call potint, the result is:
The adapter.js is from It seems that there is no package with the path of I'm not familar with it, anyone know what it is can help me explain it. For now, i just use the returned function call the middle handler: const request = req as NextRequestWithAuth;
const withAuthResult = withAuth(nextAuthOption);
if (typeof withAuthResult === 'function') {
return withAuthResult(request, event);
}
return withAuthResult; |
I'm getting the same error here |
Yep same here, we're looking forward to a fix on this. Putting a pause on our migration to Next 13 until this is stable. |
Very good catch @lantaozi, the issue is this check
With the default middleware configuration, this condition should be met, but for next@13 , it fails.cc @balazsorban44 could this be an upstream issue? There's nothing related to middleware changes in The migration doc 🤔 |
Is there any workaround for now? |
For me explicitly exporting import { withAuth } from 'next-auth/middleware'
export default withAuth({}) |
But then all routes are private, including login/logout and in that case if you log out for some reason, you are in several infinite loops |
it redirecting to the Sign In page for all the routes With a little hack around exporting import { withAuth } from "next-auth/middleware"
export const config = { matcher: ["/dashboard/:path*"] }
export default withAuth({}) |
* Migrate dev app to Next.js Version 13 * Update core types * Fix middleware #5649 * Use new ResponseCookie API vercel/next.js#41526
I am using middleware with the following content and the oAuth is done correctly, but the page always stays on the login page, no way of going to another page. I upgraded to the last release btw. Debug is enabled but no error messages. I'm using next 13.0.2
|
I was just having this same issue after upgrading to Next 13. I was using
After upgrading, nothing the version number for next-auth remained the same. I have no idea what happened, but it works |
None of the workarounds seem to work for me. It just redirects me to either login page (doesn't matter if the user is logged in or not), or doesn't do anything at all. |
Same thing ended up happening to me. This is what I eventually set my middleware file to:
The first part is a hack because there was a breaking change when publishing to production. Not also that I'm exporting the |
@jeslenbucci Unfortunately your solution doesn't work for me |
doesn't work for me, it all returns // middleware.ts
import { withAuth } from "next-auth/middleware"
export const config = { matcher: ["/api/:path*"] }
export default withAuth({}) |
@Lucasvo1 @jeslenbucci Where is the |
nextjs 13 seems quite alpha.. middleware doesnt work at all.. |
I was having trouble with withAuth() where the token was being returned null
What fixed it for me was to downgrade next js to 13.0.0 |
Even today on nextjs 13.2.4 and nextauth 4.20.1. My middleware is not working properly. I am constantly redirected to the login page when I try to access the protected routes, even after logging in. |
Any update here? I am having the same problem as above. |
Same error here with: middleware.ts import { withAuth } from 'next-auth/middleware'
export const config = {
matcher: ["/((?!auth|signin|auth/signin).*)"],
};
export default withAuth({}) If I try to access any page it redirects me to signin page, even if I'm successfully logged in |
I had the same error and updated nextjs to 13.4.5-canary.4, it allows me to compile, but still can't identify if the user is logged in or not. Commands applied
Reproduction of the problembandicam.2023-06-02.19-12-57-453.mp4middleware.ts
Versions
|
I'm still getting this. @balazsorban44 any updates ? 🙃 |
Following change worked for me:
export { default } from "next-auth/middleware";
export const config = { matcher: ["/n"] };
import type { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
export const authOptions: NextAuthOptions = {
// @ts-ignore
adapter: PrismaAdapter(prisma),
session: {
strategy: "jwt",
},
providers: [
GoogleProvider({
clientId: "****",
clientSecret: "****",
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code",
},
},
}),
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
console.log("fire signin Callback");
return true;
},
async redirect({ url, baseUrl }) {
console.log("fire redirect Callback");
return baseUrl;
},
async session({ session, user, token }) {
console.log("fire SESSION Callback");
return {
...session,
user: {
...session.user,
id: token.id,
randomKey: token.randomKey,
},
};
},
async jwt({ token, user, account, profile, isNewUser }) {
console.log("fire jwt Callback");
if (user) {
const u = user as unknown as any;
return {
...token,
id: u.id,
randomKey: u.randomKey,
};
}
return token;
},
},
}; |
Still doesnt work for me.. |
the following solution works for me export default withAuth(
function middleware(req: NextRequestWithAuth) {
//...
},
{
pages: {
signIn: LOGIN_ROUTE,
},
jwt: { decode: jwtConfig?.decode },
callbacks: {
authorized: async ({ req, token }) => {
const rawToken = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET,
decode: jwtConfig?.decode,
raw: true,
});
if (toke) return true
if (!!rawToken) {
... validate signature
return true
}
return false
},
},
secret: process.env.NEXTAUTH_SECRET,
}
); |
The following works to me in export { default } from 'next-auth/middleware'
export const config = { matcher: ['/admin/(.*)'] } Version |
import NextAuth from 'next-auth'
export default NextAuth({
secret: env.NEXTAUTH_SECRET
}) |
Still not working with app directory.... and the issue is close. This package is really difficult to use. I'm really have troubles with this |
Had the same problem with: It did work locally for some time, but for some reason it just stopped working, and no matter what - it would always stay on login page. After hours of investigation, what finally worked for me (for now) was adding: And my middleware.ts file is the same as in the comments above:
|
I got this working in the end - sorry a bit rough but sleeping for the night after pulling my hair out for a while lol
Basically I had to add an empty middleware function to get the rest of my app routes working without throwing errors, then the config worked as it did, without breaking all the pages. |
If you're using AuthJS v5 and next-intl try this middleware.ts
|
Environment
System:
OS: macOS 12.6
CPU: (8) arm64 Apple M1
Memory: 1.03 GB / 16.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 16.18.0 - ~/.nvm/versions/node/v16.18.0/bin/node
Yarn: 1.22.19 - ~/.nvm/versions/node/v16.18.0/bin/yarn
npm: 8.19.2 - ~/.nvm/versions/node/v16.18.0/bin/npm
Browsers:
Brave Browser: 106.1.44.112
Chrome: 106.0.5249.119
Firefox: 104.0.2
Safari: 16.0
Reproduction URL
.
Describe the issue
Implementing a middleware.js in Next.js 13 like described here (https://next-auth.js.org/tutorials/securing-pages-and-api-routes#nextjs-middleware) results in the following error:
How to reproduce
Implement Next-Auth with Next.js 13 and create a middleware.js with the following content:
Expected behavior
No fatal error
The text was updated successfully, but these errors were encountered: