Skip to content

Commit c221fca

Browse files
🧪 feat: add middleware for authentication and parsing requests
Implements a new middleware function in the web app for handling authentication and parsing incoming requests. - Adds a new file `apps/web/middleware.ts` for the middleware implementation. - Uses Next.js middleware API for handling requests and responses, and NextAuth's `getToken` for obtaining user session data. - Parses the request to extract the domain, path, and other information. - Redirects unauthenticated users to the sign-in page if they try to access protected routes. - Exports a `parse` function for parsing incoming requests and extracting relevant information.
1 parent a991ea0 commit c221fca

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

‎apps/web/middleware.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
2+
import { getToken } from "next-auth/jwt";
3+
4+
export default async function middleware(req: NextRequest, ev: NextFetchEvent) {
5+
const { path, fullPath } = parse(req);
6+
7+
// Use regex to match {domain}/app/* paths
8+
const appPathRegex = /^\/app\/.*/;
9+
if (!appPathRegex.test(path)) {
10+
return;
11+
}
12+
13+
const session = (await getToken({
14+
req,
15+
secret: process.env.NEXTAUTH_SECRET,
16+
})) as {
17+
uid?: string;
18+
};
19+
20+
const authIssue = !session || !session?.uid;
21+
22+
if (authIssue && (path !== "/signin" &&
23+
path !== "/signup" &&
24+
path !== "/api/auth/signin" &&
25+
path !== "/api/auth/signup" && path !== "/api/auth/providers")) {
26+
return NextResponse.redirect(
27+
new URL(
28+
`/signin${path === "/" ? "" : `?redirect=${encodeURIComponent(fullPath)}`}`,
29+
req.url,
30+
),
31+
);
32+
}
33+
34+
return;
35+
}
36+
37+
export const parse = (req: NextRequest) => {
38+
let domain = req.headers.get("host") as string;
39+
domain = domain.replace("www.", ""); // remove www. from domain
40+
41+
// path is the path of the URL (e.g. screenlink.io/view/id -> /view/id)
42+
let path = req.nextUrl.pathname;
43+
44+
// fullPath is the full URL path (along with search params)
45+
const searchParams = req.nextUrl.searchParams.toString();
46+
const fullPath = `${path}${searchParams.length > 0 ? `?${searchParams}` : ""
47+
}`;
48+
49+
// Here, we are using decodeURIComponent to handle foreign languages like Hebrew
50+
const key = decodeURIComponent(path.split("/")[1]); // key is the first part of the path (e.g. screenlink.io/view/id -> view)
51+
const fullKey = decodeURIComponent(path.slice(1)); // fullKey is the full path without the first slash (to account for multi-level subpaths, e.g. screenlink.io/view/id -> view/id)
52+
53+
return { domain, path, fullPath, key, fullKey };
54+
};

0 commit comments

Comments
 (0)