Skip to main content

@nimpl/router

Edge router for next.js apps. Allows you to configure rewrites, redirects, i18n and basePath at the middleware level instead of next.config.js.

Motivation 

All these settings are much more efficient in @nimpl/router and in edge runtime for several reasons:

  1. The Edge is best suited for redirects. Instead of the Client -> Edge -> Server -> Redirect -> Client -> Edge -> Server -> Response journey, it becomes Client -> Edge -> Redirect -> Client -> Edge -> Server -> Response. That is, instead of two long journeys to the server, the client goes to the CDN and then goes to the server only for the necessary route.
  2. Next.js i18n is full of bugs, and in the latest versions, they completely abandoned it, recommending using middleware.
  3. In middleware, you can decide for yourself which settings to enable for which paths, which rules to set, which redirect lists for /app paths, and which for /marketing. Take a look at the middleware-chain to get the most flexible and suitable configuration for you.

Installation 

Using npm:

npm i @nimpl/router

Example 

middleware.ts
import { createMiddleware } from '@nimpl/router';

export const middleware = createMiddleware({
redirects: [
{
source: '/old',
destination: '/',
permanent: false,
},
],
rewrites: [
{
source: '/home',
destination: '/',
locale: false,
},
],
basePath: '/doc',
i18n: {
defaultLocale: 'en',
locales: ['en', 'de'],
},
});

Options 

The options either completely repeat the next.js API, or they are as close as possible to them.

rewrites - absolutely identical next.js rewrites. Next.config.js/rewrites documentation 

redirects - absolutely identical next.js redirects. Next.config.js/redirects documentation 

basePath - path prefix for the application (f.e. /docs, /blog, /v2)

For flexibility, it is recommended not to use basePath in next.config.js, but to manually set the prefix in the links.

i18n - configuration for localized paths.

Unlike the next.config.js solution, it has nothing to do with Link and does not participate in the generation of page paths. That is, localization should be embedded in the structure of the application (e.g. app/[lang]/page.tsx).

Also, instead of a boolean localeDetection, the router takes a localeDetector method where you can set up how exactly to get the locale (f.e. from a CloudFlare header)

Otherwise, it repeats the logic of next.js. Next.config.js/i18n documentation 

It is recommended not to use i18n in next.config.js, but to manually set the required locale in the links.

Development 

Read about working on the package and making changes on the contribution page

Additional 

Please consider giving a star if you like it, it shows that the package is useful and helps me continue work on this and other packages.

Create issues with wishes, ideas, difficulties, etc. All of them will definitely be considered and thought over.

Previous
Middleware Chain
Next
Advanced Config
Return to navigation