forked from vercel/platforms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
67 lines (57 loc) · 2.36 KB
/
middleware.ts
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
import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
export const config = {
matcher: [
/*
* Match all paths except for:
* 1. /api routes
* 2. /_next (Next.js internals)
* 3. /fonts (inside /public)
* 4. /examples (inside /public)
* 5. all root files inside /public (e.g. /favicon.ico)
*/
"/((?!api|_next|examples|[\\w-]+\\.\\w+).*)",
],
};
export default async function middleware(req: NextRequest) {
const url = req.nextUrl;
// Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3000)
const hostname = req.headers.get("host") || "demo.vercel.pub";
// Get the pathname of the request (e.g. /, /about, /blog/first-post)
const path = url.pathname;
// Only for demo purposes - remove this if you want to use your root domain as the landing page
if (hostname === "vercel.pub" || hostname === "platforms.vercel.app") {
return NextResponse.redirect("https://demo.vercel.pub");
}
/* You have to replace ".vercel.pub" with your own domain if you deploy this example under your domain.
You can also use wildcard subdomains on .vercel.app links that are associated with your Vercel team slug
in this case, our team slug is "platformize", thus *.platformize.vercel.app works. Do note that you'll
still need to add "*.platformize.vercel.app" as a wildcard domain on your Vercel dashboard. */
const currentHost =
process.env.NODE_ENV === "production" && process.env.VERCEL === "1"
? hostname
.replace(`.vercel.pub`, "")
.replace(`.platformize.vercel.app`, "")
: hostname.replace(`.localhost:3000`, "");
// rewrites for app pages
if (currentHost == "app") {
if (
url.pathname === "/login" &&
(req.cookies.get("next-auth.session-token") ||
req.cookies.get("__Secure-next-auth.session-token"))
) {
url.pathname = "/";
return NextResponse.redirect(url);
}
url.pathname = `/app${url.pathname}`;
return NextResponse.rewrite(url);
}
// rewrite root application to `/home` folder
if (hostname === "localhost:3000" || hostname === "platformize.vercel.app") {
return NextResponse.rewrite(new URL(`/home/${path}`, req.url));
}
// rewrite everything else to `/_sites/[site] dynamic route
return NextResponse.rewrite(
new URL(`/_sites/${currentHost}${path}`, req.url)
);
}