next-auth icon indicating copy to clipboard operation
next-auth copied to clipboard

Exporting auth as middleware doesn't work

Open ShahriarKh opened this issue 2 years ago • 11 comments

Environment

OS: Windows 10 10.0.19045
Node: 20.12.2
bun: 1.1.2

Firefox Developer Edition 126.0b9

next: 14.2.3 
next-auth: 5.0.0-beta.18
react: 18.3.1

Reproduction URL

https://github.com/ShahriarKh/middleware-test

Describe the issue

Using the method mentioned in the examples and also in the docs doesn't work at all.

export { auth as middleware } from 'auth'

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

I tried switching bun/Node, and also switching Next.js version (downgraded to 14.1.0 and 14.2.0 and both had the same issue)

I have to use a custom function like this, which is not desirable:

import { auth } from 'auth'

export default auth((req) => {
  if (!req.auth) {
    const url = req.url.replace(req.nextUrl.pathname, '/login');
    return Response.redirect(url);
  }
});

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};

How to reproduce

Clone the app and visit / or /test.

Expected behavior

The middleware should automatically redirect to the login page if the request is unauthenticated.

ShahriarKh avatar May 14 '24 16:05 ShahriarKh

Same error here! The workaround that I found was using request cookies to check for session-token and validating it by using an api route. Here is my code:

// middleware.ts
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

export async function middleware(req: NextRequest) {
  const cookies = req.cookies;

  if (!cookies.get("authjs.session-token")) {
    return NextResponse.redirect(new URL("/login", req.url));
  } else {
    try {
      const sessionResponse = await fetch(
        `${req.nextUrl.origin}/api/auth/session`,
        {
          headers: {
            cookie: req.headers.get("cookie") || "", // Pass cookies to the API route
          },
        }
      );
      if (sessionResponse.status !== 200) {
        throw new Error("Session not found");
      }
    } catch (error) {
      
      console.log(error);
      const response = NextResponse.redirect(new URL("/login", req.url));
      response.cookies.set('authjs.session-token', '', { expires: new Date(0) });
      return response;
    }
  }
  return NextResponse.next();
}

export const config = {
  matcher: "/admin/:path*",
};
// api/auth/session/route.ts
import { auth } from "@/auth";
import { NextResponse } from "next/server";
import { Session } from "next-auth";

export async function GET() {
  const session: Session | null = await auth();
  if (!session) {
    return NextResponse.json({ message: "Auth required" }, { status: 401 });
  }
  return NextResponse.json({ message: "succc" }, { status: 200 });
}

MateusTum avatar May 15 '24 22:05 MateusTum

Same error here! The workaround that I found was using request cookies to check for session-token and validating it by using an api route. Here is my code:

// middleware.ts
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

export async function middleware(req: NextRequest) {
  const cookies = req.cookies;

  if (!cookies.get("authjs.session-token")) {
    return NextResponse.redirect(new URL("/login", req.url));
  } else {
    try {
      const sessionResponse = await fetch(
        `${req.nextUrl.origin}/api/auth/session`,
        {
          headers: {
            cookie: req.headers.get("cookie") || "", // Pass cookies to the API route
          },
        }
      );
      if (sessionResponse.status !== 200) {
        throw new Error("Session not found");
      }
    } catch (error) {
      
      console.log(error);
      const response = NextResponse.redirect(new URL("/login", req.url));
      response.cookies.set('authjs.session-token', '', { expires: new Date(0) });
      return response;
    }
  }
  return NextResponse.next();
}

export const config = {
  matcher: "/admin/:path*",
};
// api/auth/session/route.ts
import { auth } from "@/auth";
import { NextResponse } from "next/server";
import { Session } from "next-auth";

export async function GET() {
  const session: Session | null = await auth();
  if (!session) {
    return NextResponse.json({ message: "Auth required" }, { status: 401 });
  }
  return NextResponse.json({ message: "succc" }, { status: 200 });
}

This workaround works so far. I hope a fix will be released soon

drxc00 avatar May 22 '24 15:05 drxc00

I am also experiencing a problem with incorrect req type definition in middleware. Is it the same for you?

No overload matches this call.
  Overload 1 of 4, '(args_0: GetServerSidePropsContext): Promise<Session | null>', gave the following error.
    Argument of type '(req: NextAuthRequest) => Response | null' is not assignable to parameter of type 'GetServerSidePropsContext'.
  Overload 2 of 4, '(args_0: (req: NextAuthRequest, ctx: AppRouteHandlerFnContext) => void | Response | Promise<void | Response>): AppRouteHandlerFn', gave the following error.
    Argument of type '(req: NextAuthRequest) => Response | null' is not assignable to parameter of type '(req: NextAuthRequest, ctx: AppRouteHandlerFnContext) => void | Response | Promise<void | Response>'.
      Type 'Response | null' is not assignable to type 'void | Response | Promise<void | Response>'.
        Type 'null' is not assignable to type 'void | Response | Promise<void | Response>'.ts(2769)

image

bibblebabl avatar May 23 '24 10:05 bibblebabl

@bibblebabl same

drcodecamp avatar Jun 08 '24 20:06 drcodecamp

Same error here! The workaround that I found was using request cookies to check for session-token and validating it by using an api route. Here is my code:

// middleware.ts
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

export async function middleware(req: NextRequest) {
  const cookies = req.cookies;

  if (!cookies.get("authjs.session-token")) {
    return NextResponse.redirect(new URL("/login", req.url));
  } else {
    try {
      const sessionResponse = await fetch(
        `${req.nextUrl.origin}/api/auth/session`,
        {
          headers: {
            cookie: req.headers.get("cookie") || "", // Pass cookies to the API route
          },
        }
      );
      if (sessionResponse.status !== 200) {
        throw new Error("Session not found");
      }
    } catch (error) {
      
      console.log(error);
      const response = NextResponse.redirect(new URL("/login", req.url));
      response.cookies.set('authjs.session-token', '', { expires: new Date(0) });
      return response;
    }
  }
  return NextResponse.next();
}

export const config = {
  matcher: "/admin/:path*",
};
// api/auth/session/route.ts
import { auth } from "@/auth";
import { NextResponse } from "next/server";
import { Session } from "next-auth";

export async function GET() {
  const session: Session | null = await auth();
  if (!session) {
    return NextResponse.json({ message: "Auth required" }, { status: 401 });
  }
  return NextResponse.json({ message: "succc" }, { status: 200 });
}

This workaround works so far. I hope a fix will be released soon

FYI At least from what I found, the cookie name for me appears to be set as __Secure-authjs.session-token instead of just authjs.session-token on a site deployed to vercel that I was testing. Locally this was working for me fine, but once deployed still wasnt working and believe that is why. Still using a modified version of this to check for both so appreciate the workaround!

dl-web-dev avatar Jun 09 '24 01:06 dl-web-dev

Same error here.

BertVanHeckeCertifisc avatar Jun 13 '24 09:06 BertVanHeckeCertifisc

import NextAuth from 'next-auth';
import { authConfig } from './auth.config';

const { auth } = NextAuth(authConfig);

export default async function middleware(...args: Parameters<typeof auth>) {
  return auth(...args);
}

export const config = {
  matcher: [ 'matchers/'],
};

This is what I use and it works fine for me. I'm on 5.0.0-beta.19

surya-teja-222 avatar Jun 13 '24 17:06 surya-teja-222

I am also experiencing a problem with incorrect req type definition in middleware. Is it the same for you?

No overload matches this call.
  Overload 1 of 4, '(args_0: GetServerSidePropsContext): Promise<Session | null>', gave the following error.
    Argument of type '(req: NextAuthRequest) => Response | null' is not assignable to parameter of type 'GetServerSidePropsContext'.
  Overload 2 of 4, '(args_0: (req: NextAuthRequest, ctx: AppRouteHandlerFnContext) => void | Response | Promise<void | Response>): AppRouteHandlerFn', gave the following error.
    Argument of type '(req: NextAuthRequest) => Response | null' is not assignable to parameter of type '(req: NextAuthRequest, ctx: AppRouteHandlerFnContext) => void | Response | Promise<void | Response>'.
      Type 'Response | null' is not assignable to type 'void | Response | Promise<void | Response>'.
        Type 'null' is not assignable to type 'void | Response | Promise<void | Response>'.ts(2769)
image

Hi @bibblebabl , this issue can be resolved if you write return; in place of return null; for all occurrences. In short, remove the null from return and return nothing. The messaeg also suggests Type 'Response | null' is not assignable to type 'void | Response | Promise<void | Response>'. which means null is not accepted, and uses void instead.

subhajit100 avatar Jun 18 '24 09:06 subhajit100

Looks like the main problem is that https://authjs.dev/getting-started/session-management/protecting#nextjs-middleware forgets to mention the authorized callback: https://authjs.dev/reference/nextjs#authorized

If anyone wants to add it to the getting started docs, feel free to open a PR!

Suggestions here about fetch-ing the /api/auth/session should not be followed, as it will decrease your app's performance significantly, by doing an unnecessary network call on every single page request.

balazsorban44 avatar Jun 20 '24 01:06 balazsorban44

This issue was marked with the good first issue label by a maintainer.

This means that it is a good candidate for someone interested in contributing to the project, but does not know where to start.

Have a look at the Contributing Guide first.

This will help you set up your development environment to get started. When you are ready, open a PR, and link back to this issue in the form of adding Fixes #1234 to the PR description, where 1234 is the issue number. This will auto-close the issue when the PR gets merged, making it easier for us to keep track of what has been fixed.

Please make sure that - if applicable - you add tests for the changes you make.

If you have any questions, feel free to ask in the comments below or the PR. Generally, you don't need to @mention anyone directly, as we will get notified anyway and will respond as soon as we can)

[!NOTE]
There is no need to ask for permission "can I work on this?" Please, go ahead if there is no linked PR :slightly_smiling_face:

github-actions[bot] avatar Jun 20 '24 01:06 github-actions[bot]

I'm still getting this issue.

export { auth as middleware } from "./auth"

works on dev server, but does not work when hosted on vercel.

If I write the logic in the middleware.ts it works as expected, but this is not the described functionality.

jcourson-bg avatar Sep 18 '25 15:09 jcourson-bg