2022-03-21 03:46:15 -04:00
|
|
|
import { NextFetchEvent, NextRequest, NextResponse } from 'next/server'
|
|
|
|
|
|
|
|
const PUBLIC_FILE = /.(.*)$/
|
|
|
|
|
2022-03-21 15:45:35 -04:00
|
|
|
export function middleware(req: NextRequest) {
|
2022-03-21 03:46:15 -04:00
|
|
|
const pathname = req.nextUrl.pathname
|
2022-03-21 04:15:37 -04:00
|
|
|
const signedIn = req.cookies['drift-token']
|
|
|
|
const getURL = (pageName: string) => new URL(`/${pageName}`, req.url).href
|
2022-03-21 03:46:15 -04:00
|
|
|
// const isPageRequest =
|
|
|
|
// !PUBLIC_FILE.test(req.nextUrl.pathname) &&
|
|
|
|
// !req.nextUrl.pathname.startsWith('/api') &&
|
|
|
|
// // header added when next/link pre-fetches a route
|
|
|
|
// !req.headers.get('x-middleware-preflight')
|
|
|
|
|
2022-03-21 04:15:37 -04:00
|
|
|
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');
|
2022-03-21 04:36:31 -04:00
|
|
|
resp.clearCookie('drift-userid');
|
|
|
|
|
2022-03-21 04:15:37 -04:00
|
|
|
return resp
|
|
|
|
}
|
|
|
|
} else if (pathname === '/') {
|
|
|
|
if (signedIn) {
|
2022-03-28 19:19:53 -04:00
|
|
|
return NextResponse.redirect(getURL('new'))
|
2022-03-21 03:46:15 -04:00
|
|
|
}
|
|
|
|
// If you're not signed in we redirect the new post page to the home page
|
|
|
|
} else if (pathname === '/new') {
|
2022-03-21 04:15:37 -04:00
|
|
|
if (!signedIn) {
|
2022-03-28 19:19:53 -04:00
|
|
|
return NextResponse.redirect(getURL('signin'))
|
2022-03-21 03:46:15 -04:00
|
|
|
}
|
|
|
|
// If you're signed in we redirect the sign in page to the home page (which is the new page)
|
2022-03-21 04:36:31 -04:00
|
|
|
} else if (pathname === '/signin' || pathname === '/signup') {
|
2022-03-21 04:15:37 -04:00
|
|
|
if (signedIn) {
|
|
|
|
return NextResponse.redirect(getURL(''))
|
2022-03-21 03:46:15 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return NextResponse.next()
|
|
|
|
}
|