中间件.ts
export { default } from 'next-auth/middleware';
export const config = { matcher: ['/my/:path*'] };
https://next-auth.js.org/configuration/nextjs#middleware
现在我像这样使用,但代码不起作用
我希望中间件在访问与“我的”相关的页面时能够正常工作。 我该如何修复它?
"next": "^12.0.8",
"next-auth": "^4.10.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
这是我的软件包版本
pages/api/auth/[...nextauth].ts
import NextAuth, { NextAuthOptions } from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import { prisma } from '@/lib/prismadb';
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID || '',
clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
}),
],
session: { strategy: 'jwt' },
};
export default NextAuth({
...authOptions,
});
中间件.ts
import { getToken } from 'next-auth/jwt';
import { NextRequest, NextResponse } from 'next/server';
export default async function middleware(req: NextRequest) {
// Get the pathname of the request (e.g. /, /protected)
const path = req.nextUrl.pathname;
// If it's the root path, just render it
if (path === '/') {
return NextResponse.next();
}
const session = await getToken({
req,
secret: process.env.NEXTAUTH_SECRET,
});
const isProtected = path.includes('/dashboard');
if (!session && isProtected) {
return NextResponse.redirect(new URL('/restore', req.url));
} else if (session && (path === '/restore' || path === '/register')) {
return NextResponse.redirect(new URL('/dashboard', req.url));
}
return NextResponse.next();
}
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
export default async function middleware(req: NextRequest) {
const path = req.nextUrl.pathname;
const session = !!req.cookies.get("next-auth.session-token")
if (!session) {
return NextResponse.redirect(new URL(`/api/auth/signin?callbackUrl=${path}`, req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)','/boards', '/workspace/:path*']
}
,middleware.ts (js)需要放入文件夹内,这将起作用。 Lahiru Lanka Rathnayaka谢谢您的回答)
通过升级到 next 的金丝雀版本(13.4.5-canary.0)修复了这个问题,不过你可以等到 nextjs 13.4.5 稳定版本发布后再升级。
升级到 nextjs 的最新金丝雀版本
install --save next@canary
…
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"middleware.ts"
],
…