MCPcopy Create free account
hub / github.com/api-platform/website / middleware

Function middleware

pwa/middleware.tsx:28–91  ·  view source on GitHub ↗
(request: NextRequest)

Source from the content-addressed store, hash-verified

26}
27
28export async function middleware(request: NextRequest) {
29 const { locales, defaultLocale } = i18n;
30 const pathname = request.nextUrl.pathname;
31
32 // handle current doc version to skip the version in pathname (removes this when next will support optionnal parameter)
33 if (
34 pathname.startsWith("/docs/") &&
35 !/\.(jpg|jpeg|png|gif|svg)$/.test(pathname)
36 ) {
37 if (pathname.startsWith(`/docs/v${current}`)) {
38 const url = new URL(pathname.replace(`v${current}/`, ""), request.url);
39 const response = NextResponse.redirect(url);
40 return response;
41 }
42
43 const isMissingVersion = versions.every(
44 (version) => !pathname.startsWith(`/docs/v${version}/`)
45 );
46
47 if (isMissingVersion) {
48 return NextResponse.rewrite(
49 new URL(pathname.replace("/docs/", `/docs/v${current}/`), request.url)
50 );
51 }
52 }
53
54 if (
55 !pathname.startsWith("/fr/con") &&
56 !pathname.startsWith("/en/con") &&
57 !pathname.startsWith("/con")
58 ) {
59 return NextResponse.next();
60 }
61
62 // Check if the default locale is in the pathname
63 if (pathname.startsWith(`/${defaultLocale}/`)) {
64 // we want to REMOVE the default locale from the pathname,
65 // and later use a rewrite so that Next will still match
66 // the correct code file as if there was a locale in the pathname
67 const url = new URL(pathname.replace(`${defaultLocale}/`, ""), request.url);
68 const response = NextResponse.redirect(url);
69 response.cookies.set("redirected", "true", { maxAge: 10 });
70 return response;
71 }
72
73 // Check if there is any supported locale in the pathname
74 const pathnameIsMissingLocale = locales.every(
75 (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
76 );
77
78 // Redirect if there is no locale
79 if (pathnameIsMissingLocale) {
80 const matchedLocale = getLocale(request);
81 if (matchedLocale !== defaultLocale && !request.cookies.get("redirected")) {
82 return NextResponse.redirect(
83 new URL(`/${matchedLocale}/${pathname}`, request.url)
84 );
85 } else {

Callers

nothing calls this directly

Calls 1

getLocaleFunction · 0.85

Tested by

no test coverage detected