-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
82 lines (71 loc) · 2.53 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import {
authMiddleware,
redirectToSignIn,
clerkMiddleware,
createRouteMatcher,
} from '@clerk/nextjs/server';
const isProtectedRoute = createRouteMatcher(['/app/']);
import { NextRequest, NextResponse } from 'next/server';
// import { getToken } from 'next-auth/jwt';
export const config = {
matcher: [
/*
* Match all paths except for:
* 1. /api routes
* 2. /_next (Next.js internals)
* 3. /_static (inside /public)
* 4. all root files inside /public (e.g. /favicon.ico)
*/
'/((?!api/|_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)',
],
};
export default authMiddleware({
publicRoutes: ['/'],
afterAuth: (auth, req) => {
const url = req.nextUrl;
// Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3123)
// biome-ignore lint/style/noNonNullAssertion: <explanation>
let hostname = req.headers
.get('host')!
.replace('.localhost:3000', `.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`);
// special case for Vercel preview deployment URLs
if (
hostname.includes('---') &&
hostname.endsWith(`.${process.env.NEXT_PUBLIC_VERCEL_DEPLOYMENT_SUFFIX}`)
) {
hostname = `${hostname.split('---')[0]}.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`;
}
const searchParams = req.nextUrl.searchParams.toString();
// Get the pathname of the request (e.g. /, /about, /blog/first-post)
const path = `${url.pathname}${searchParams.length > 0 ? `?${searchParams}` : ''}`;
// rewrites for app pages
if (hostname === `app.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`) {
if (!auth.userId && path.split('-')[0] !== '/sign') {
const prefix =
process.env.NODE_ENV === 'development' ? 'http://' : 'https://';
return NextResponse.redirect(`${prefix}${hostname}/sign-in`);
}
return NextResponse.rewrite(
new URL(`/app${path === '/' ? '' : path}`, req.url),
);
}
// special case for `vercel.pub` domain
// if (hostname === 'vercel.pub') {
// return NextResponse.redirect(
// 'https://vercel.com/blog/platforms-starter-kit',
// );
// }
// rewrite root application to `/home` folder
if (
hostname === 'localhost:3000' ||
hostname === process.env.NEXT_PUBLIC_ROOT_DOMAIN
) {
return NextResponse.rewrite(
new URL(`/home${path === '/' ? '' : path}`, req.url),
);
}
// console.log("here");
// rewrite everything else to `/[domain]/[slug] dynamic route
return NextResponse.rewrite(new URL(`/${hostname}${path}`, req.url));
},
});