Skip to content

Commit f2a26c2

Browse files
authored
feat: introduce new middleware engine (#5396)
1 parent 8eade10 commit f2a26c2

File tree

5 files changed

+115
-53
lines changed

5 files changed

+115
-53
lines changed

middleware.ts

Lines changed: 7 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,11 @@
11
import { NextResponse } from 'next/server';
2-
import localeConfig from './i18n/config.json';
3-
import type { NextRequest } from 'next/server';
2+
import createMiddleware from './next.middleware';
43

5-
// As set of available and enabled locales for the website
6-
// This is used for allowing us to redirect the user to any
7-
// of the available locales that we have enabled on the website
8-
const localeCodes = localeConfig
9-
.filter(locale => locale.enabled)
10-
.map(locale => locale.code);
4+
const nextMiddleware = createMiddleware(NextResponse);
115

12-
export async function middleware(req: NextRequest) {
13-
const { pathname, search } = req.nextUrl;
6+
const { middleware, matcher } = nextMiddleware([
7+
// eslint-disable-next-line @typescript-eslint/no-var-requires
8+
require('./middlewares/detectLanguage').default,
9+
]);
1410

15-
// This function allows us to redirect with a Locale Code
16-
const redirectWithLocale = (locale: string) => {
17-
const redirectUrl = `/${locale}${pathname}${search}`;
18-
19-
return NextResponse.redirect(new URL(redirectUrl, req.url));
20-
};
21-
22-
const localeCookie = req.cookies.get('NEXT_LOCALE');
23-
24-
// If we already have a NEXT_LOCALE Cookie, then Redirect to the stored Locale Code
25-
if (localeCookie && localeCookie.value) {
26-
return redirectWithLocale(localeCookie.value);
27-
}
28-
29-
// If not, we try to check if the Browser is sending `Accept-Language` Header
30-
const acceptedLanguagesRaw = req.headers.get('Accept-Language') || 'en';
31-
32-
// If present, we try to split the format into ['code', 'q=order', ...]
33-
// Where q= is the precedence of the Accepted Language
34-
// We then filter those out as we don't want them
35-
const acceptedLanguages = acceptedLanguagesRaw
36-
.split(';')
37-
.map(collection => collection.split(','))
38-
.flat()
39-
.filter(locale => !locale.startsWith('q='));
40-
41-
// We check if we have any matching Language in the order of preference given
42-
// And if yes, we return that Locale Code
43-
const matchedLocaleCode = acceptedLanguages.find(acceptedLocale =>
44-
localeCodes.some(supportedLocale => supportedLocale === acceptedLocale)
45-
);
46-
47-
// We create a new Response Object containing the Locale Match or the default Language
48-
const responseWithCookie = redirectWithLocale(matchedLocaleCode || 'en');
49-
50-
// Then we set a Cookie to avoid this calculation from happening on every / hit
51-
responseWithCookie.cookies.set('NEXT_LOCALE', matchedLocaleCode || 'en');
52-
53-
return responseWithCookie;
54-
}
55-
56-
export const config = { matcher: '/' };
11+
export { middleware, matcher };

middlewares/detectLanguage.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import type { CustomMiddleware } from '../types';
2+
3+
const detectLanguage: CustomMiddleware = {
4+
handler: async (request, response, { availableLocales }) => {
5+
const { pathname, search } = request.nextUrl;
6+
7+
// This function allows us to redirect with a Locale Code
8+
const redirectWithLocale = (_locale: string) => {
9+
const redirectUrl = `/${_locale}${pathname}${search}`;
10+
11+
return response.redirect(new URL(redirectUrl, request.url));
12+
};
13+
14+
const localeCookie = request.cookies.get('NEXT_LOCALE');
15+
16+
// If we already have a NEXT_LOCALE Cookie, then Redirect to the stored Locale Code
17+
if (localeCookie?.value && localeCookie.value !== 'default') {
18+
return redirectWithLocale(localeCookie.value);
19+
}
20+
21+
// If not, we try to check if the Browser is sending `Accept-Language` Header
22+
const acceptedLanguagesRaw = request.headers.get('Accept-Language') || 'en';
23+
24+
// If present, we try to split the format into ['code', 'q=order', ...]
25+
// Where q= is the precedence of the Accepted Language
26+
// We then filter those out as we don't want them
27+
const acceptedLanguages = acceptedLanguagesRaw
28+
.split(';')
29+
.map(collection => collection.split(','))
30+
.flat()
31+
.filter(locale => !locale.startsWith('q='));
32+
33+
// We check if we have any matching Language in the order of preference given
34+
// And if yes, we return that Locale Code
35+
const matchedLocaleCode = acceptedLanguages.find(acceptedLocale =>
36+
availableLocales.some(locale => locale === acceptedLocale)
37+
);
38+
39+
// We create a new Response Object containing the Locale Match or the default Language
40+
const responseWithCookie = redirectWithLocale(matchedLocaleCode || 'en');
41+
42+
// Then we set a Cookie to avoid this calculation from happening on every / hit
43+
responseWithCookie.cookies.set('NEXT_LOCALE', matchedLocaleCode || 'en');
44+
45+
return responseWithCookie;
46+
},
47+
matcher: request => request.nextUrl.pathname === '/',
48+
routes: ['/'],
49+
};
50+
51+
export default detectLanguage;

next.middleware.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { availableLocales, getCurrentLocale } from './next.locales.mjs';
2+
import type { NextRequest, NextResponse } from 'next/server';
3+
import type { CustomMiddleware, NextMiddlewareLocale } from './types';
4+
5+
const availableLocaleCodes = availableLocales.map(locale => locale.code);
6+
7+
const createMiddleware = (response: typeof NextResponse) => {
8+
const localeMiddleware = (request: NextRequest): NextMiddlewareLocale => {
9+
const currentLocale = getCurrentLocale(request.nextUrl.pathname);
10+
11+
return {
12+
currentLocale: currentLocale.code,
13+
availableLocales: availableLocaleCodes,
14+
isLocalisedRoute: currentLocale.code !== 'en',
15+
};
16+
};
17+
18+
return (middlewares: CustomMiddleware[]) => {
19+
const middleware = async (request: NextRequest) => {
20+
const locale = localeMiddleware(request);
21+
22+
const matchedMiddleware = middlewares.find(middleware =>
23+
middleware.matcher(request, locale)
24+
);
25+
26+
if (matchedMiddleware) {
27+
return matchedMiddleware.handler(request, response, locale);
28+
}
29+
30+
return response.next();
31+
};
32+
33+
const matcher = middlewares.map(middleware => middleware.routes).flat();
34+
35+
return { middleware, matcher };
36+
};
37+
};
38+
39+
export default createMiddleware;

types/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// @TODO: These types will be splitted on individual files for better organisation in the future
21
import type { AppProps as DefaultAppProps } from 'next/app';
32

43
import type { BlogData } from './blog';
@@ -15,6 +14,7 @@ export * from './navigation';
1514
export * from './nodeVersions';
1615
export * from './prevNextLink';
1716
export * from './releases';
17+
export * from './middlewares';
1818

1919
export interface AppProps {
2020
nodeVersionData: Array<NodeVersionData>;

types/middlewares.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import type { NextRequest, NextResponse } from 'next/server';
2+
3+
export type NextMiddlewareLocale = {
4+
isLocalisedRoute: boolean;
5+
currentLocale: string | null;
6+
availableLocales: string[];
7+
};
8+
9+
export type CustomMiddleware = {
10+
handler: (
11+
request: NextRequest,
12+
response: typeof NextResponse,
13+
locale: NextMiddlewareLocale
14+
) => Promise<NextResponse>;
15+
matcher: (request: NextRequest, locale: NextMiddlewareLocale) => boolean;
16+
routes: string[];
17+
};

0 commit comments

Comments
 (0)