client: don't run middleware if the request isn't a page

This commit is contained in:
Max Leiter 2022-04-01 21:17:33 -07:00
parent f927fae9ed
commit ce01eba9c0
No known key found for this signature in database
GPG key ID: A3512F2F2F17EBDA

View file

@ -1,41 +1,43 @@
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from 'next/server'
// const PUBLIC_FILE = /.(.*)$/ const PUBLIC_FILE = /.(.*)$/
export function middleware(req: NextRequest) { export function middleware(req: NextRequest) {
const pathname = req.nextUrl.pathname const pathname = req.nextUrl.pathname
const signedIn = req.cookies['drift-token'] const signedIn = req.cookies['drift-token']
const getURL = (pageName: string) => new URL(`/${pageName}`, req.url).href const getURL = (pageName: string) => new URL(`/${pageName}`, req.url).href
// const isPageRequest = const isPageRequest =
// !PUBLIC_FILE.test(req.nextUrl.pathname) && !PUBLIC_FILE.test(req.nextUrl.pathname) &&
// !req.nextUrl.pathname.startsWith('/api') && !req.nextUrl.pathname.startsWith('/api') &&
// // header added when next/link pre-fetches a route // header added when next/link pre-fetches a route
// !req.headers.get('x-middleware-preflight') !req.headers.get('x-middleware-preflight')
if (isPageRequest) {
if (pathname === '/signout') {
// If you're signed in we remove the cookie and redirect to the home page
// If you're not signed in we redirect to the home page
if (signedIn) {
const resp = NextResponse.redirect(getURL(''));
resp.clearCookie('drift-token');
resp.clearCookie('drift-userid');
if (pathname === '/signout') { return resp
// If you're signed in we remove the cookie and redirect to the home page }
// If you're not signed in we redirect to the home page } else if (pathname === '/') {
if (signedIn) { if (signedIn) {
const resp = NextResponse.redirect(getURL('')); return NextResponse.redirect(getURL('new'))
resp.clearCookie('drift-token'); }
resp.clearCookie('drift-userid'); // If you're not signed in we redirect the new post page to the home page
} else if (pathname === '/new') {
return resp if (!signedIn) {
} return NextResponse.redirect(getURL('signin'))
} else if (pathname === '/') { }
if (signedIn) { // If you're signed in we redirect the sign in page to the home page (which is the new page)
return NextResponse.redirect(getURL('new')) } else if (pathname === '/signin' || pathname === '/signup') {
} if (signedIn) {
// If you're not signed in we redirect the new post page to the home page return NextResponse.redirect(getURL(''))
} else if (pathname === '/new') { }
if (!signedIn) {
return NextResponse.redirect(getURL('signin'))
}
// If you're signed in we redirect the sign in page to the home page (which is the new page)
} else if (pathname === '/signin' || pathname === '/signup') {
if (signedIn) {
return NextResponse.redirect(getURL(''))
} }
} }
return NextResponse.next() return NextResponse.next()
} }