Next.js Discord

Discord Forum

Hey guys I am trying to implement auth v5 and next-intl together does anyone had worked with it ?

Unanswered
California pilchard posted this in #help-forum
Open in Discord
California pilchardOP
Problem is that middleware has always some problem and it's loading wiht error and I dont know how exactly fix it this is my middleware
import { NextRequest, NextResponse } from 'next/server';
import createMiddleware from 'next-intl/middleware';
import { routing } from './i18n/routing';
import NextAuth from 'next-auth';
import authConfig from '@/auth.config';
import {
  DEFAULT_LOGIN_REDIRECT,
  apiAuthPrefix,
  authRoutes,
  publicRoutes
} from "@/routes";

const { auth } = NextAuth(authConfig);

const middleware = async (req: any) => {
  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);

  console.log("ROUTE: ", nextUrl.pathname);
  console.log("Logged in:", isLoggedIn);
  console.log("Public route:", isPublicRoute);

  const intlMiddleware = createMiddleware(routing);
  const intlResponse = await intlMiddleware(req);

  if (intlResponse) {
    if (!isLoggedIn && !isPublicRoute) {
      return NextResponse.redirect(new URL('/en/auth/sign-in', nextUrl));
    }

    return intlResponse;
  }

  if (isApiAuthRoute) {
    return NextResponse.next();
  }

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

  if (!isLoggedIn && !isPublicRoute) {
    return NextResponse.redirect(new URL('/en/auth/sign-in', nextUrl));
  }

  return NextResponse.next();
};

export default auth(middleware);

export const config = {
  matcher: ['/', '/(en|sk|cz)/:path*','/(en|sk|cz)/auth:path*', '/((?!api|_next|_vercel|.*\\..*).*)']
};

0 Replies