Get an array of all pages within the Next.js
/pages/ directory using Webpack's
require.context function. Jump to the code
If you've ever wanted to display a list of all your current Next.js pages but have not found a way, you're in luck because there's actually a way in doing so! This method will involve using
webpack and will only for work projects using it.
We'll use this example Next.js project structure:
nextjs-project/ └── pages/ ├── _app.js ├── _document.js ├── index.js ├── about.js └── stuff/ ├── secret.js └── index.js
The trick here is to use the
require.context function that comes with webpack. By using this function, we'll be able to read all of the files and directories inside of the
const ctx = require.context('./', true, /\.js$/);
This first parameter should point to your
/pages/ directory. The second parameter is set to
true so that webpack can read all subdirectories. The third parameter is a regular expression that finds only the
.js files. Without this, Webpack will assume that we want to grab other file extensions like
The code above will output an array of files/directories when calling the
.keys() method on
[ "./_app.js", "./_document.js", "./index.js", "./about.js", "./stuff/index.js", "./stuff/secret.js" ]
Now, we'll need to clean this up a bit and filter out the files/directories that we don't need so that the output is much more URL friendly:
[ "/", "/about", "/stuff", "/stuff/secret" ]
A working demo can be found here on CodeSandbox.
Note: You should probably put
getPages function inside a Utilities directory, or not, I'm not your dad.
Since this only runs during build time, your production app should have already generated the list of pages.