Next.js Discord

Discord Forum

Middleware redirection issue

Unanswered
Faizan posted this in #help-forum
Open in Discord
I'm working on a project where I need to check if the browser url path contains one of the strings, if not I need to redirect user to 404 page. I'm logging a message when the conditions doesn't match but not able to navigate to 404 page.

code snippet is attached, I've tried many other ways too

import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server';
const validStoreCodes = [
  'sg',
  'my',
  'id',
  'us',
  'intl',
  'hk'
]
export function middleware(request: NextRequest) {
  const nextUrl = request.nextUrl.clone()
  const pathName = nextUrl.pathname
  if (!validStoreCodes.some(storeCode => pathName.startsWith(`/${storeCode}`))) {
    console.log('URL doesn\'nt start with a valid store code', request.nextUrl.pathname)
  }
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-url', pathName);
 
  // You can also set request headers in NextResponse.rewrite
  const response = NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  });
  return response;

}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico|logo.svg|404|not-found).*)'],
}

0 Replies