Skip to content

Support middleware for session-based authenticationΒ #4259

@GeeWee

Description

@GeeWee

Description πŸ““

Next-auth recently introduced middleware that validates JWT-tokens, which is a great step usability-wise.

Unfortunately those of us who are using alternate authentication methods such as session-based authentication don't have anything out of the box, and implementing a middleware like that yourself is trickier than you would expect, because you cannot simply pass the request in your middleware to getSession

This seems to be because the next-auth accesses headers via req.headers.cookie, but the type of the headers inside middleware is not an object, but a Headers object which must be accessed through req.headers.get("cookie")

I have implemented a middleware that works for session-based authentication. It does this by converting the relevant part of the request headers to an object

import type { NextFetchEvent, NextRequest } from 'next/server';
import { getSession } from 'next-auth/react';
import { NextResponse } from 'next/server';

export async function middleware(req: NextRequest, ev: NextFetchEvent) {
  const requestForNextAuth = {
    headers: {
      cookie: req.headers.get('cookie'),
    },
  };

  const session = await getSession({ req: requestForNextAuth });

  if (session) {
    console.log(session);

    // validate your session here

    return NextResponse.next();
  } else {
    // the user is not logged in, redirect to the sign-in page
    const signInPage = '/auth/signin';
    const signInUrl = new URL(signInPage, req.nextUrl.origin);
    signInUrl.searchParams.append('callbackUrl', req.url);
    return NextResponse.redirect(signInUrl);
  }
}

However I think this means that an extra fetch call will be made to the next-auth backend. One in the middleware, and one later on if you want to access the session in API calls.

Solution proposal 1: Middleware

It would be great if next-auth provided a middleware that did everything, like it does for the JWT-based flow

Solution proposal 2: Allow NextRequest in GetSession

Another great solution, which probably requires less work is to accept a NextRequest in getSession, which meant it could be used both client-side, server-side and in middleware.

It does not seem like there are many code changes needed to make this work.

Related issues:
#3136
#4042
#3151

How to reproduce β˜•οΈ

N/A

Contributing πŸ™ŒπŸ½

Yes, I am willing to help implement this feature in a PR

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions