forked from dewodt/just-do-list
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
32 lines (28 loc) · 988 Bytes
/
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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import url from "url"
export default async function middleware(
req: NextRequest,
) {
const [ cookies ] = req.cookies.getAll();
const reqUrl = req.url;
// Find homeUrl and subdirectory
const parsedUrl = url.parse(reqUrl, true);
const subdirectory = parsedUrl.pathname?.split("/")[1] as string;
const homeUrl = reqUrl.replace(subdirectory, "")
if (!cookies) {
if (subdirectory === "") {
// If there's no cookie, login.
return NextResponse.rewrite(homeUrl);
} else {
// If there's no cookie and wrong page, 404.
return NextResponse.rewrite(`${homeUrl}404`);
}
} else {
if (subdirectory === "") {
// There's cookie and go to login page, redirect to tasks
return NextResponse.redirect(`${homeUrl}tasks`);
} // else can go to any page available
}
}
export const config = { matcher: "/((?!api|static|.*\\..*|_next).*)" };