Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

withAuth module not exported in next-auth in Next.js

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
like image 438
n9p4 Avatar asked Nov 17 '25 13:11

n9p4


2 Answers

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

like image 63
n9p4 Avatar answered Nov 20 '25 04:11

n9p4


use auth() if on the "beta"/v5+ version of next-auth; auth() used in lieu of withAuth; refer to:

  • https://authjs.dev/guides/upgrade-to-v5
  • https://authjs.dev/guides/upgrade-to-v5#authenticating-server-side

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+.

like image 20
user19009041 Avatar answered Nov 20 '25 04:11

user19009041



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!