QuiiBz / next-international

Type-safe internationalization (i18n) for Next.js
https://next-international.vercel.app
MIT License
1.19k stars 52 forks source link

next-international with authjs V5 middleware ? #326

Closed Robin-Afg closed 6 months ago

Robin-Afg commented 6 months ago

how to construct the middleware so the next-international works with next-auth v5 middleware?

QuiiBz commented 6 months ago

Checkout the previous issues: https://github.com/QuiiBz/next-international/issues/224 https://github.com/QuiiBz/next-international/issues/94

Robin-Afg commented 6 months ago

Hello again,

I think in the Next Auth(V5) which is released recently they have changed a couple of things so the pervious workarounds does not really help in my knowledge. My middleware code is down below and i really don't know how to chain this two middleware. Can I request a reproduction of this code Thanks again

import { createI18nMiddleware } from "next-international/middleware";
import NextAuth from "next-auth";
import authConfig from "./auth.config";
import {
  DEFAULT_LOGIN_REDIRECT,
  apiAuthPrefix,
  authRoutes,
  publicRoutes,
} from "@/routes";

const { auth } = NextAuth(authConfig);

const I18Middleware = createI18nMiddleware({
  locales: ["en", "dr", "ps"],
  defaultLocale: "en",
});

export default auth((req) => {
  // req.auth
  const { nextUrl } = req;
  const isLoggedIn = !!req.auth;
  const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
  const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
  const isAuthRoute = authRoutes.includes(nextUrl.pathname);

  if (isApiAuthRoute) {
    return null;
  }

  if (isAuthRoute) {
    if (isLoggedIn) {
      return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
    }
    return null;
  }

  if (!isLoggedIn && !isPublicRoute) {
    return Response.redirect(new URL("/auth/login", nextUrl));
  }

  return I18Middleware(req);
   return null;
});

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
QuiiBz commented 6 months ago

Looking at their documentation, it seems like the next-auth package is deprecated in v5:

Screenshot 2024-01-08 at 17 24 40

I'm not familiar with authjs v5, but you might want to ask the same in their GitHub issues because this isn't related to next-international directly.