All files / Rindu middleware.ts

96% Statements 24/25
88.88% Branches 8/9
100% Functions 2/2
95.45% Lines 21/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52  1x             1x   1x   3x 3x 3x 3x 3x 3x 2x   2x               7x   1x 1x 1x   1x 1x   1x 1x               1x 1x        
import type { NextRequest } from "next/server";
import { NextResponse, userAgentFromString } from "next/server";
 
import {
  DEFAULT_LOCALE,
  isLocale,
  LOCALE_COOKIE,
  parseAcceptLanguage,
} from "utils";
 
const PUBLIC_FILE = /\.(.*)$/;
 
export function middleware(request: NextRequest): NextResponse | void {
  const isApiRoute = request.nextUrl.pathname.startsWith("/api");
  const isNextRoute = request.nextUrl.pathname.startsWith("/_next");
  const isPublicFile = PUBLIC_FILE.test(request.nextUrl.pathname);
  const userAgent = request.headers.get("User-Agent");
  if (!userAgent) return;
  const userAgentObject = userAgentFromString(userAgent);
 
  const ignoreMiddleware = [
    isNextRoute,
    isApiRoute,
    isPublicFile,
    userAgentObject.isBot,
    !userAgentObject.browser.name,
  ];
 
  if (ignoreMiddleware.some((condition) => condition)) return;
 
  const acceptLanguage = request.headers.get("Accept-Language");
  const userLocales = parseAcceptLanguage(acceptLanguage ?? "");
  const locale = userLocales.find(isLocale) ?? DEFAULT_LOCALE;
 
  const localeCookie = request.cookies.get(LOCALE_COOKIE)?.value;
  const localeCookieValue = localeCookie ?? locale;
 
  if (!localeCookie) {
    const rewriteResponse = NextResponse.rewrite(request.nextUrl, {
      request: {
        headers: new Headers({
          ...request.headers,
          "x-locale": localeCookieValue,
        }),
      },
    });
    rewriteResponse.cookies.set(LOCALE_COOKIE, localeCookieValue);
    return rewriteResponse;
  }
  return NextResponse.next();
}