-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
93 lines (75 loc) · 2.64 KB
/
proxy.ts
File metadata and controls
93 lines (75 loc) · 2.64 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { i18n } from "./i18n-config";
import { match as matchLocale } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
function getLocale(request: NextRequest): string | undefined {
// Negotiator expects plain object so we need to transform headers
const negotiatorHeaders: Record<string, string> = {};
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));
// @ts-expect-error locales are readonly
const locales: string[] = i18n.locales;
// Use negotiator and intl-localematcher to get best locale
const languages = new Negotiator({ headers: negotiatorHeaders }).languages(
locales
);
const locale = matchLocale(languages, locales, i18n.defaultLocale);
return locale;
}
const PUBLIC_FILE = /\.(.*)$/;
export function proxy(request: NextRequest) {
// Basic Auth
if (
process.env.NODE_ENV !== "development" &&
process.env.BASIC_AUTH_USERNAME &&
process.env.BASIC_AUTH_PASSWORD
) {
const basicAuth = request.headers.get("authorization");
if (!basicAuth) {
return new Response("Authentication required", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Secure Area"',
},
});
}
try {
const authValue = basicAuth.split(" ")[1];
const [user, pwd] = atob(authValue).split(":");
if (
user !== process.env.BASIC_AUTH_USERNAME ||
pwd !== process.env.BASIC_AUTH_PASSWORD
) {
return new Response("Unauthorized", { status: 401 });
}
} catch (e) {
return new Response("Invalid Authentication", { status: 400 });
}
}
const pathname = request.nextUrl.pathname;
// skips adding the public files
if (PUBLIC_FILE.test(pathname)) {
return;
}
// Check if there is any supported locale in the pathname
const pathnameIsMissingLocale = i18n.locales.every(
(locale) =>
!pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
);
// Redirect if there is no locale
if (pathnameIsMissingLocale) {
const locale = getLocale(request);
// e.g. incoming request is /products
// The new URL is now /en-US/products
return NextResponse.redirect(
new URL(
`/${locale}${pathname.startsWith("/") ? "" : "/"}${pathname}`,
request.url
)
);
}
}
export const config = {
// Matcher ignoring `/_next/` and `/api/`
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};