Update middleware docs to use cookies for protected routes #579

Closed
opened 2026-03-13 07:54:34 -05:00 by GiteaMirror · 1 comment
Owner

Originally created by @daveycodez on GitHub (Jan 21, 2025).

Describe the solution you'd like

According to Next.js head of developer relations (https://www.youtube.com/watch?si=_rgPzz8PHodJpQjO&t=682&v=N_sUsq_y10U&feature=youtu.be) it is against best practices to perform any UI blocking or HTTP requests in middleware, and middleware should be used for optimistic routing whereas the actual route protection should happen on the route itself.

Describe alternatives you've considered

Use cookies

const protectedRoutes: string[] = ["/dashboard"]

export async function middleware(request: NextRequest) {
    if (protectedRoutes.includes(request.nextUrl.pathname)) {
        if (!request.cookies.has("better-auth.session_token")) {
            return NextResponse.redirect(new URL("/", request.url))
        }
    }

   return NextResponse.next()
}

It would be great to have better-auth auth.ts export a hasCookie function that checks for cookies so we don't have to hardcode the cookie name here.

Also something like getCookieSession that optimistically verifies session_data cookie and returns it, no HTTP requests or DB queries.

Originally created by @daveycodez on GitHub (Jan 21, 2025). ### Describe the solution you'd like According to Next.js head of developer relations (https://www.youtube.com/watch?si=_rgPzz8PHodJpQjO&t=682&v=N_sUsq_y10U&feature=youtu.be) it is against best practices to perform any UI blocking or HTTP requests in middleware, and middleware should be used for optimistic routing whereas the actual route protection should happen on the route itself. ### Describe alternatives you've considered Use cookies ```ts const protectedRoutes: string[] = ["/dashboard"] export async function middleware(request: NextRequest) { if (protectedRoutes.includes(request.nextUrl.pathname)) { if (!request.cookies.has("better-auth.session_token")) { return NextResponse.redirect(new URL("/", request.url)) } } return NextResponse.next() } ``` It would be great to have better-auth auth.ts export a hasCookie function that checks for cookies so we don't have to hardcode the cookie name here. Also something like getCookieSession that optimistically verifies session_data cookie and returns it, no HTTP requests or DB queries.
Author
Owner

@Bekacru commented on GitHub (Jan 22, 2025):

good suggestion

@Bekacru commented on GitHub (Jan 22, 2025): good suggestion
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#579