Created
August 11, 2023 07:26
-
-
Save paulpopus/9f8d726e2cc2f531126f9d16f1319dda to your computer and use it in GitHub Desktop.
Nextjs Middleware for Payload authentication to redirect users based on authentication
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 { NextResponse } from 'next/server' | |
import type { NextRequest } from 'next/server' | |
import { CheckUserDocument } from '@/graphql/generated/client' | |
import { CheckUserQuery } from '@/graphql/generated/client' | |
/* Redirect away from these routes if not authenticated */ | |
const protectedRoutes = ['/profile', '/search'] | |
/* Redirect away from these routes if authenticated */ | |
const publicRoutes = ['/login', '/register'] | |
export async function middleware(request: NextRequest) { | |
const protectedRoute = protectedRoutes.find((route) => { | |
return request.nextUrl.pathname.startsWith(route) | |
}) | |
if (protectedRoute) { | |
const hasToken = request.cookies.has('payload-token') | |
if (hasToken) { | |
const token = request.cookies.get('payload-token') | |
if (token?.value) { | |
const user: CheckUserQuery = await fetch(process.env.NEXT_PUBLIC_API_URL, { | |
method: 'POST', | |
...{ credentials: 'include', headers: { 'content-type': 'application/json', Authorization: `JWT ${token?.value}` } }, | |
body: JSON.stringify({ query: CheckUserDocument, variables: {} }), | |
}) | |
.then((data) => data.json()) | |
.then((data) => data.data) | |
if (!user.meUser?.token) { | |
return NextResponse.redirect(new URL(`/login?message=LOG_IN&redirect=${protectedRoute}`, request.url)) | |
} | |
} else { | |
return NextResponse.redirect(new URL(`/login?message=LOG_IN&redirect=${protectedRoute}`, request.url)) | |
} | |
} else { | |
return NextResponse.redirect(new URL(`/login?message=LOG_IN&redirect=${protectedRoute}`, request.url)) | |
} | |
} | |
const publicRoute = publicRoutes.find((route) => { | |
return request.nextUrl.pathname.startsWith(route) | |
}) | |
if (publicRoute) { | |
const hasToken = request.cookies.has('payload-token') | |
if (hasToken) { | |
const token = request.cookies.get('payload-token') | |
if (token?.value) { | |
const user: CheckUserQuery = await fetch(process.env.NEXT_PUBLIC_API_URL, { | |
method: 'POST', | |
...{ credentials: 'include', headers: { 'content-type': 'application/json', Authorization: `JWT ${token?.value}` } }, | |
body: JSON.stringify({ query: CheckUserDocument, variables: {} }), | |
}) | |
.then((data) => data.json()) | |
.then((data) => data.data) | |
if (user.meUser?.token) { | |
return NextResponse.redirect(new URL(`/`, request.url)) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment