Created
March 24, 2024 19:11
-
-
Save wdevon99/3e958d965b93706873f89ffd476e17f4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { NextRequest, NextResponse } from "next/server"; | |
| import { getToken } from "next-auth/jwt"; | |
| const PROTECTED_API_ROUTES = ["/api/todo"]; | |
| const PROTECTED_ROUTES = ["/dashboard"]; | |
| export async function middleware(request: NextRequest) { | |
| const isProtectedApiRoute = PROTECTED_API_ROUTES.some((route: string) => request.nextUrl?.pathname?.startsWith(route)); | |
| const isProtectedRoute = PROTECTED_ROUTES.some((route: string) => request.nextUrl?.pathname?.startsWith(route)); | |
| if (isProtectedApiRoute) { | |
| const isAuth = await isAuthenticated(request); | |
| if (!isAuth) { | |
| return Response.json({ success: false, message: "Authentication failed" }, { status: 401 }); | |
| } | |
| } | |
| if (isProtectedRoute) { | |
| const isAuth = await isAuthenticated(request); | |
| if (!isAuth) { | |
| return NextResponse.redirect(new URL("/", request.url)); | |
| } | |
| } | |
| return NextResponse.next(); | |
| } | |
| const isAuthenticated = async (request: NextRequest) => { | |
| const token: any = await getToken({ req: request }); | |
| return !!token && Date.now() <= token.exp * 1000; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment