Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Middleware refactoring #314

Merged
merged 1 commit into from
Feb 8, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 17 additions & 16 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,34 @@ const PUBLIC_FILE = /\.(.*)$/
const logger = getLogger('middleware')

export async function middleware(req: NextRequest) {
const { cookies, nextUrl, url } = req
const { locale, pathname } = nextUrl

if (
req.nextUrl.pathname.startsWith('/_next') ||
req.nextUrl.pathname.includes('/api/') ||
PUBLIC_FILE.test(req.nextUrl.pathname)
pathname.startsWith('/_next') ||
pathname.includes('/api/') ||
PUBLIC_FILE.test(pathname)
) {
return
return NextResponse.next()
}

logger.debug(req)

if (req.nextUrl.locale === 'default' && !req.nextUrl.pathname.endsWith('/')) {
return NextResponse.redirect(new URL(`/en${req.nextUrl.pathname}`, req.url))
if (locale === 'default' && !pathname.endsWith('/')) {
return NextResponse.redirect(new URL(`/en${pathname}`, url))
}

//Redirect for index page as it's meant to be bilingual so we don't want users navigating to /en or /fr
if (
(req.nextUrl.locale === 'en' || req.nextUrl.locale === 'fr') &&
req.nextUrl.pathname === '/'
) {
return NextResponse.redirect(new URL(`/`, req.url))
if ((locale === 'en' || locale === 'fr') && pathname === '/') {
return NextResponse.redirect(new URL(`/`, url))
}

if (
!['/', '/expectations'].includes(req.nextUrl.pathname) &&
req.cookies.get('agreed-to-email-esrf-terms') !== 'true'
!['/', '/expectations'].includes(pathname) &&
cookies.get('agreed-to-email-esrf-terms') !== 'true'
) {
return NextResponse.redirect(
new URL(`/${req.nextUrl.locale}/expectations`, req.url)
)
return NextResponse.redirect(new URL(`/${locale}/expectations`, url))
}

return NextResponse.next()
}