[GH-ISSUE #333] nextjs auth middleware session is null and causes infinite redirect loop #8225

Closed
opened 2026-04-13 03:19:24 -05:00 by GiteaMirror · 3 comments
Owner

Originally created by @firstaxel on GitHub (Oct 25, 2024).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/333

Describe the bug
A clear and concise description of what the bug is.
Any time I implement using the authMiddleware in my nextjs app it cause infinite loop and when I check the session returns null thereby redirecting me to the login page countless times

To Reproduce
Steps to reproduce the behavior:

Just follow the integration guide on nextjs

Expected behavior
A clear and concise description of what you expected to happen.
Supposed to return session after the users is logged in and does not cause infinite redirect to the login page.

Additional context
Add any other context about the problem here.
Version is 0.5.3 beta16
Nextjs 14.2.16

Originally created by @firstaxel on GitHub (Oct 25, 2024). Original GitHub issue: https://github.com/better-auth/better-auth/issues/333 **Describe the bug** A clear and concise description of what the bug is. Any time I implement using the authMiddleware in my nextjs app it cause infinite loop and when I check the session returns null thereby redirecting me to the login page countless times **To Reproduce** Steps to reproduce the behavior: Just follow the integration guide on nextjs **Expected behavior** A clear and concise description of what you expected to happen. Supposed to return session after the users is logged in and does not cause infinite redirect to the login page. **Additional context** Add any other context about the problem here. Version is 0.5.3 beta16 Nextjs 14.2.16
GiteaMirror added the locked label 2026-04-13 03:19:24 -05:00
Author
Owner

@firstaxel commented on GitHub (Oct 25, 2024):

@benmccann you can check it out

<!-- gh-comment-id:2437214896 --> @firstaxel commented on GitHub (Oct 25, 2024): @benmccann you can check it out
Author
Owner

@koohz commented on GitHub (Oct 25, 2024):

Start posting also your middleware.ts, and maybe your auth.ts and auth-client.ts

<!-- gh-comment-id:2437310399 --> @koohz commented on GitHub (Oct 25, 2024): Start posting also your middleware.ts, and maybe your auth.ts and auth-client.ts
Author
Owner

@ghost commented on GitHub (Oct 25, 2024):

I seem to be experiencing the same issue:

middleware.ts file:

import { authMiddleware } from "better-auth/next-js";
import { NextResponse } from "next/server";

export default authMiddleware({
  customRedirect: async (session, request) => {
    const baseURL = request.nextUrl.origin;
    if (request.nextUrl.pathname === "/auth/sign-in" && session) {
      return NextResponse.redirect(new URL("/dashboard", baseURL));
    }
    if (request.nextUrl.pathname === "/dashboard" && !session) {
      return NextResponse.redirect(new URL("/auth/sign-in", baseURL));
    }
    return NextResponse.next();
  },
});

export const config = {
  matcher: ["/dashboard", "/auth/sign-in"],
};

auth-client.ts:

import { createAuthClient } from "better-auth/react";
import toast from "react-hot-toast";

export const authClient = createAuthClient({
  baseURL: "http://localhost:3000",
  fetchOptions: {
    onError(e) {
      if (e.error.status === 429) {
        toast.error("Too many requests. Please try again later.");
      }
    },
  },
});

auth.ts:

import { db } from "../db";
import { user, session, account, verification } from "../db/auth-schema";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";

export const authService = betterAuth({
  database: drizzleAdapter(db, {
    provider: "pg",
    schema: {
      user,
      session,
      account,
      verification,
    },
  }),
  rateLimit: {
    window: 30,
    max: 50,
    storage: "database",
    tableName: "rateLimit",
  },
  emailAndPassword: {
    enabled: true,
  },
  trustedOrigins: ["http://localhost:3000"],
});

For starters, I initially checked if the request was obtaining the necessary cookie header

inside middleware.ts:

console.log(request.headers)

The request itself does contain both the better-auth.csrf_token cookie as well as the better-auth.session_token cookie, with correct values.

I then try logging the session, from within the middleware file:

console.log(session);

As per the issue at hand, it returns null

Am I doing anything incorrectly?

P.S everything has worked fine up to this point, db is populated upon login, entries deleted upon logout etc.

<!-- gh-comment-id:2438610872 --> @ghost commented on GitHub (Oct 25, 2024): I seem to be experiencing the same issue: middleware.ts file: ```js import { authMiddleware } from "better-auth/next-js"; import { NextResponse } from "next/server"; export default authMiddleware({ customRedirect: async (session, request) => { const baseURL = request.nextUrl.origin; if (request.nextUrl.pathname === "/auth/sign-in" && session) { return NextResponse.redirect(new URL("/dashboard", baseURL)); } if (request.nextUrl.pathname === "/dashboard" && !session) { return NextResponse.redirect(new URL("/auth/sign-in", baseURL)); } return NextResponse.next(); }, }); export const config = { matcher: ["/dashboard", "/auth/sign-in"], }; ``` auth-client.ts: ```js import { createAuthClient } from "better-auth/react"; import toast from "react-hot-toast"; export const authClient = createAuthClient({ baseURL: "http://localhost:3000", fetchOptions: { onError(e) { if (e.error.status === 429) { toast.error("Too many requests. Please try again later."); } }, }, }); ``` auth.ts: ```js import { db } from "../db"; import { user, session, account, verification } from "../db/auth-schema"; import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; export const authService = betterAuth({ database: drizzleAdapter(db, { provider: "pg", schema: { user, session, account, verification, }, }), rateLimit: { window: 30, max: 50, storage: "database", tableName: "rateLimit", }, emailAndPassword: { enabled: true, }, trustedOrigins: ["http://localhost:3000"], }); ``` For starters, I initially checked if the request was obtaining the necessary cookie header inside middleware.ts: ```js console.log(request.headers) ``` The request itself does contain both the `better-auth.csrf_token` cookie as well as the `better-auth.session_token` cookie, with correct values. I then try logging the session, from within the middleware file: ```js console.log(session); ``` As per the issue at hand, it returns `null` Am I doing anything incorrectly? P.S everything has worked fine up to this point, db is populated upon login, entries deleted upon logout etc.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#8225