1

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.

Minsik Park
  • 557
  • 3
  • 9
  • 22

3 Answers3

2

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
Sabrina Luo
  • 3,810
  • 4
  • 16
  • 35
1

You can create a custom server to serve that one page. So, all other pages will be served by Next.js and a specific one by the custom server. Just don't put this page to /pages so you won't get a routing conflict.

Nikolai Kiselev
  • 6,201
  • 2
  • 27
  • 37
0

The easiest way would be renaming those routes/files from 'file.js' to just 'file' (or any other extensions as you would prefer) which will then be ignored by next.js

Agneesh Bose
  • 211
  • 3
  • 4