I am trying to add a middleware in the route /admin at next.js, and in the file " _middleware.js" it is like this:
import { withAuth } from "next-auth/middleware";
export default withAuth({
callbacks: {
authorized({ req, token }) {
if (token) return true; // If there is a token, the user is authenticated
},
},
});
Error:
./pages/admin/_middleware.js:1:0
Module not found: Package path ./middleware is not exported from package
Path:
pages
|-------admin
|--------------_middleware.js
|--------------index.js
The solution, update your nextAuth dependence. withAuth was an update at 4.2.0. https://github.com/nextauthjs/next-auth/releases/tag/v4.2.0 Special thanks to juliomalves
use auth() if on the "beta"/v5+ version of next-auth; auth() used in lieu of withAuth; refer to:
a very crude example:
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
/*
* middleware.js
*
* see: https://nextjs.org/docs/app/building-your-application/routing/middleware
*/
export default function middleware(request: NextRequest) {
// log every request
let datetime = new Date().toString().substring(0, 33);
console.log(`${datetime} ${request.method} ${request.nextUrl.pathname}`);
// run auth
auth();
};
and auth.ts:
import type { NextAuthConfig } from 'next-auth';
import NextAuth from 'next-auth';
/*
* lib/auth.ts
*/
const providers = [
[...]
];
export const config = {
theme: {
logo: "https://next-auth.js.org/img/logo/logo-sm.png",
},
providers: providers,
callbacks: {
authorized({ request, auth }) {
const { pathname } = request.nextUrl
if (pathname === "/middleware-example") return !!auth
return true
},
},
} satisfies NextAuthConfig;
export const { handlers, auth, signIn, signOut } = NextAuth(config);
note: as of 2024-JAN, one might be on the "beta" version if you are avoiding the edge runtime issues on 4.X and Next.js v14+.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With