Search code examples
next.js

middleware ignored nextjs having it on root


I have my middleware.js file in my project root, nextjs version is 12.3.1

This is my middleware.js

import { NextResponse, NextRequest } from "next/server";

const PUBLIC_FILE = /\.(.*)$/

/**
 *
 * @param {NextRequest} req
 * @returns {NextResponse}
 */
export function middleware(req) {

  console.log('locale', req.nextUrl.locale);

  try {
    if(
      req.nextUrl.pathname.startsWith('/_next') ||
      req.nextUrl.pathname.includes('/api/') ||
      PUBLIC_FILE.test(req.nextUrl?.pathname)
    ) return NextResponse.next();

    if (req.nextUrl.locale === 'default') {
      return NextResponse.redirect(new URL(`/en${req.nextUrl.pathname}`, req.url));
    }

    return NextResponse.next();
  } catch(error) {
    console.error(error);
    return NextResponse.redirect(new URL(`/`, req.url));
  }

}

I also tried with

export function middleware(req) {
  console.log('locale', req.nextUrl.locale);
  return NextResponse.next();
}

And I have the same issue, also with return NextResponse.redirect(new URL('/en', req.url)); replacing the console.log to be sure it was not a logging issue but no redirect

This is my next.config.js

const path = require("path");
const { withSentryConfig } = require("@sentry/nextjs");
const { i18n } = require("./next-i18next.config");

const nextConfig = {
    reactStrictMode: true,
    i18n,
    sentry: {
      hideSourceMaps: true
    },
    sassOptions: {
        includePaths: [path.join(__dirname, "./src/styles/")],
        prependData: `
      @import "_colors.scss";
      @import "_fonts.scss";
      @import "_mixins.scss";
      @import "_responsive.scss";
      @import "_variable.scss";`,
    },
};

module.exports = withSentryConfig(nextConfig, {silent: true});

and my next-i18next.config

const path = require("path");

module.exports = {
    i18n: {
        defaultLocale: "default",
        locales: ["en", "fr", "es", "default"],
        localeDetection: true
    },
    serializeConfig: false,
};

I did many tests and can not understand why my middleware is ignored


Solution

  • Ok, I found the issue.

    The middleware has to be on the same level as the pages, not on root.

    In my case, the correct configuration is

    /src/pages
    /src/middleware.js
    

    Here is the link to the documentation (Pages and App Router): https://nextjs.org/docs/pages/building-your-application/routing/middleware#convention