forked from ixartz/SaaS-Boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
71 lines (59 loc) · 1.86 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
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';
import {
type NextFetchEvent,
type NextRequest,
NextResponse,
} from 'next/server';
import createMiddleware from 'next-intl/middleware';
import { AllLocales, AppConfig } from './utils/AppConfig';
const intlMiddleware = createMiddleware({
locales: AllLocales,
localePrefix: AppConfig.localePrefix,
defaultLocale: AppConfig.defaultLocale,
});
const isProtectedRoute = createRouteMatcher([
'/dashboard(.*)',
'/:locale/dashboard(.*)',
'/onboarding(.*)',
'/:locale/onboarding(.*)',
]);
export default function middleware(
request: NextRequest,
event: NextFetchEvent,
) {
if (
request.nextUrl.pathname.includes('/sign-in') ||
request.nextUrl.pathname.includes('/sign-up') ||
isProtectedRoute(request)
) {
return clerkMiddleware((auth, req) => {
const authObj = auth();
if (isProtectedRoute(req)) {
const locale =
req.nextUrl.pathname.match(/(\/.*)\/dashboard/)?.at(1) ?? '';
const signInUrl = new URL(`${locale}/sign-in`, req.url);
authObj.protect({
// `unauthenticatedUrl` is needed to avoid error: "Unable to find `next-intl` locale because the middleware didn't run on this request"
unauthenticatedUrl: signInUrl.toString(),
});
}
if (
authObj.userId &&
!authObj.orgId &&
req.nextUrl.pathname.includes('/dashboard') &&
!req.nextUrl.pathname.endsWith('/organization-selection')
) {
const orgSelection = new URL(
'/onboarding/organization-selection',
req.url,
);
return NextResponse.redirect(orgSelection);
}
return intlMiddleware(req);
})(request, event);
}
return intlMiddleware(request);
}
export const config = {
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};