Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make disable file system routing for specific page in nextjs

How can I block file system routing for only one page in nextjs?

In spite of using Custom server, I can not apply useFileSystemPublicRoutes : false option because some pages is still accessed through file system router.

is there another way? or is it best to me to register every page on custom server and use useFileSystemPublicRoutes : false option?

Thanks in advance.

like image 255
Minsik Park Avatar asked Aug 30 '25 15:08

Minsik Park


1 Answers

You can either use rewrites or redirects in next.config.js (Next v10.1 or above), you won't need a custom server.

You don't need to disable the useFileSystemPublicRoutes option, because as you said some pages should still be accessed.

let's say you have the below page folder structure:

pages
  ├── file_accessible.tsx
  ├── file_should_be_disabled.tsx
  ├── file_accessible_by_different_route.tsx
  

Assuming you have a 404 page, here is an example of using redirects

module.exports = {
  async redirects() {
    return [
      {
        source: '/file_should_be_disabled',  // this path will be redirected to 404 
        destination: '/404',
        permanent: true,
      },
      {
        source: '/abc', 
        destination: '/file_accessible_by_different_route', // when visiting /abc, you will be redirected to this path
      },
    ]
  },
}

Both rewrites and redirects and solve you problem, in case you also want to know the difference between rewrites and redirects:

Rewrites act as a URL proxy and mask the destination path, making it appear the user hasn't changed their location on the site. In contrast, redirects will reroute to a new page and show the URL changes.

ref:

  1. https://nextjs.org/docs/api-reference/next.config.js/rewrites
  2. https://nextjs.org/docs/api-reference/next.config.js/redirects
like image 112
Sabrina Luo Avatar answered Sep 02 '25 08:09

Sabrina Luo