49 lines
2.2 KiB
JavaScript
49 lines
2.2 KiB
JavaScript
import { isValidLocale } from './helpers.js';
|
|
import { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js';
|
|
/** Re-exported so the project's proxy.ts config uses the plugin's matcher. */ export const DEFAULT_PROXY_MATCHER = DEFAULT_MIDDLEWARE_MATCHER;
|
|
/**
|
|
* Ready-made Next 16 proxy (the former middleware). Wraps the plugin's locale
|
|
* logic AND the per-project boilerplate (NextResponse, x-locale / x-pathname
|
|
* headers, locale cookie, redirect). The project's proxy.ts becomes a few lines.
|
|
*
|
|
* `NextResponse` is INJECTED (the plugin never imports next/server — it's a peer
|
|
* dep absent at the plugin's build time). The project passes it:
|
|
*
|
|
* // proxy.ts (Next 16 — NOT middleware.ts)
|
|
* import { NextResponse } from 'next/server'
|
|
* import { createProxy, DEFAULT_PROXY_MATCHER } from '@intecion/ipal-kit'
|
|
* import { i18nConfig } from '@/i18n.config'
|
|
* export const proxy = createProxy(i18nConfig, { NextResponse })
|
|
* export const config = { matcher: DEFAULT_PROXY_MATCHER }
|
|
*/ export function createProxy(config, deps) {
|
|
const { exposeHeaders = true, NextResponse, ...mwOptions } = deps;
|
|
const run = createLocaleMiddleware({
|
|
config,
|
|
...mwOptions
|
|
});
|
|
return (request)=>{
|
|
const result = run(request);
|
|
const requestHeaders = new Headers(request.headers);
|
|
if (exposeHeaders) {
|
|
const { pathname } = request.nextUrl;
|
|
const seg = pathname.split('/').filter(Boolean)[0] ?? '';
|
|
const locale = isValidLocale(seg, config) ? seg : config.defaultLocale;
|
|
requestHeaders.set('x-locale', locale);
|
|
requestHeaders.set('x-pathname', pathname);
|
|
}
|
|
const response = result.type === 'redirect' ? NextResponse.redirect(new URL(result.location, request.url)) : NextResponse.next({
|
|
request: {
|
|
headers: requestHeaders
|
|
}
|
|
});
|
|
if (result.cookie) {
|
|
response.cookies.set(result.cookie.name, result.cookie.value, {
|
|
path: '/',
|
|
sameSite: 'lax'
|
|
});
|
|
}
|
|
return response;
|
|
};
|
|
}
|
|
|
|
//# sourceMappingURL=createProxy.js.map
|