Middleware

createNextMiddleware

API reference for the createNextMiddleware() method.

Overview

createNextMiddleware is a utility that creates a middleware function for use with Next.js. It lets you add a distinct route for each locale in your Next.js application.

For example, a French user would be directed to /fr/landing and an English user to /en/landing.

For more information on using this middleware, see the i18n routing guide.

Reference

Props

Prop

Type

Description

PropDescription
pathConfigA nested object that specifies localised paths for your application.
localeRoutingA flag to enable or disable i18n routing.
prefixDefaultLocaleA flag to enable or disable removing the locale prefix from the default locale (e.g. /en/about/about).

Example

Basic usage

Simply call this function and add the path matcher to your middleware file to enable locale routing.

middleware.js
import { createNextMiddleware } from 'gt-next/middleware'

export default createNextMiddleware();

export const config = {
  matcher: [
    /*
      * Match all request paths except those starting with:
      * - api (API routes)
      * - _next (internal files)
      * - static files
      */
    "/((?!api|static|.*\\..*|_next).*)",
  ],
}

Localised paths

You can specify localised paths via the pathConfig option in the middleware file.

middleware.js
export default createNextMiddleware({
  pathConfig: {
    "/about": "/about",
    "/airplanes": {
      "zh": "/飞机",
    }
  },
});

See the i18n routing guide for a detailed explanation of how this works.

Remove the default locale prefix

You can remove the default locale prefix by setting the prefixDefaultLocale option to false.

middleware.js
export default createNextMiddleware({
  prefixDefaultLocale: true,
});

When this is true, every path must be prefixed with the locale. If you set this to false (the default), only the default locale will be removed from the path.


Notes

  • The createNextMiddleware function is a utility that creates a middleware function for use with Next.js.

Next steps

How is this guide?

createNextMiddleware