-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
52 lines (41 loc) · 1.58 KB
/
Copy pathmiddleware.ts
File metadata and controls
52 lines (41 loc) · 1.58 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
import { auth } from "@/auth";
import createMiddleware from "next-intl/middleware";
import { routing } from "./i18n/routing";
import { NextRequest, NextResponse } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
const intlMiddleware = createMiddleware(routing);
function getLocale(request: NextRequest): string {
const headers = {
"accept-language": request.headers.get("accept-language") || undefined,
};
const negotiator = new Negotiator({ headers });
const languages: readonly string[] = negotiator.languages() || [];
return match(languages, routing.locales, routing.defaultLocale);
}
export default auth((req) => {
const originalUrl = new URL(req.url);
const pathSegments = originalUrl.pathname.split("/").filter(Boolean);
const locale = getLocale(req) || routing.defaultLocale;
if (!locale && pathSegments.length > 0) {
return NextResponse.redirect(
new URL(`/${routing.defaultLocale}/404`, req.url)
);
}
const intlResponse = intlMiddleware(req);
const rawPath = pathSegments.slice(locale ? 1 : 0).join("/") || "/";
const isPublicRoute = rawPath === "login";
const isLoggedIn = !!req.auth?.user;
if (!isLoggedIn) {
return rawPath === "/"
? NextResponse.redirect(new URL(`/${locale}/login`, req.url))
: NextResponse.next();
}
if (isLoggedIn && isPublicRoute) {
return NextResponse.redirect(new URL(`/${locale}`, req.url));
}
return intlResponse || NextResponse.next();
});
export const config = {
matcher: ["/((?!api|_next/static|_next/image|icons).*)"],
};