Captain
Captain

Reputation: 133

Prevent some components inside /pages folder to become a route in NextJS

As I need an /about route in NextJS, I've created the following folder structure:

...
 |
pages/
 |
 ├── about/
       |
       ├── index.js
       |
       ├── AboutContent.jsx
 

Where AboutContent.jsx is just a component to help index.js with part of the logic. The problem is that the AboutContent.jsx has become a route:/about/AboutContent. How do I prevent non-index.js components to become routes?

Upvotes: 6

Views: 5915

Answers (3)

felixmosh
felixmosh

Reputation: 35493

Move it out of the pages folder.

pages folder must have only page components, rest of the components you can put in your src folder.

 |
pages/
 |
 ├── about/
       |
       ├── index.js
src/
 |
 ├── AboutContent.jsx

just import AboutContent from the src folder

Edit

in Next.js v13+ there is a new concept folder which calls app which allows you to have components inside it, this concept converts only the index.js files to routes.

Upvotes: 8

tronx.dev
tronx.dev

Reputation: 138

In BETA [email protected], you can move your pages and components to /app directory while it is still okay to keep the page components under /pages directory. But routes across /app and /pages directories should not resolve to the same URL path. It may cause a build-time exception. I recommend to upgrade your Next.js to the latest and put all pages in /app directory.

 |
app/
 |
 ├── about/
       |
       |-- AbountContent.js
       ├── layout.js
       |-- page.js

 |
ui/
 |
 |-- BaseComponent.js

Upvotes: 0

Lucas Maracaipe
Lucas Maracaipe

Reputation: 307

You can colocate test files or other files used by components in the pages directory. Inside next.config.js, add the pageExtensions config:

module.exports = {
  pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
}

https://nextjs.org/docs/api-reference/next.config.js/custom-page-extensions

Upvotes: 5

Related Questions