In Next.js, by default, all pages are located in the pages folder under the project root directory. However, if you want to customize the directory structure for pages—such as organizing them across different directories—you can achieve this with simple configuration changes.
Step 1: Modify next.config.js
First, locate or create a next.config.js file in the project's root directory. This file serves as the central configuration for Next.js, enabling you to manage various advanced settings.
Step 2: Use the dir option
Within the next.config.js file, specify a custom directory path using the dir option. This path replaces the default project root as the base directory for Next.js. For example, to place all page files in the custom folder under the project root, configure it as follows:
javascript// next.config.js module.exports = { dir: './custom', };
Step 3: Organize your page files
Create a pages directory inside the custom folder and structure your page files as usual. For instance:
shellproject-root/ |- custom/ |- pages/ |- index.js |- about.js
Example Code
Suppose you have an about.js page:
javascript// /custom/pages/about.js import React from 'react'; const About = () => { return <div>About Us</div>; }; export default About;
Now, regardless of whether your pages reside in custom/pages or any other directory you specify, Next.js will correctly identify and route them.
Notes
- The
dirconfiguration only alters the base directory Next.js uses when searching for JavaScript and Markdown files; other configurations and file organization remain unaffected. - After making these changes, restart your development server to apply the configuration.
By implementing this approach, you can flexibly structure your Next.js project to meet diverse development requirements and preferences.