1

I have a next js application which has multiple lingual support. So I have a middleware to redirect users to URL with the locale. I want to implement auth js in this application.

export function middleware(request: any) {
  const pathname = request.nextUrl.pathname;

  const pathnameIsMissingLocale = locales.every(
    (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
  );

  if (pathnameIsMissingLocale) {
    const locale = getLocale(request);

    return NextResponse.redirect(
      new URL(`/${locale}/${pathname}`, request.url)
    );
  }
}

export const config = {
  matcher: [
    // Skip all internal paths (_next, assets, api)
    //"/((?!api|assets|.*\\..*|_next).*)",
    "/((?!api|assets|docs|.*\\..*|_next).*)",
    // Optional: only run on root (/) URL
  ],
};

In this application, I want to implement authentication using auth.js v5. According to the docs, I have to add the below snippet in the middleware without any matcher.

import { auth as middleware } from "@/lib/auth";

How to resolve this issue? TIA

Renaming one of the functions doesn't help as it has to be middleware for it work.

1 Answer 1

0

This is how we set up a middleware along with next-auth.

import { NextRequest, NextResponse } from "next/server"
import { auth } from "auth" // auth.ts file

export default auth((request: NextRequest) => {
    // @ts-ignore
    const { auth } = request
    console.log("auth", auth)

    // TIP: this is how we set custom headers to be used in our application
    const headers = new Headers(request.headers)
    headers.set("x-current-path", request.nextUrl.pathname)
    return NextResponse.next({
        request: {
            headers: headers as Headers
        }
    })
})

export const config = {
    matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.