nextjs get a list of all the pages in a directory


To get a list of all the pages in a directory in a Next.js app, you can use the fs module from the Node.js standard library to read the directory and get a list of all the file names. Here’s an example of how you can do this:

const fs = require('fs');
const path = require('path');

const pagesDirectory = path.join(__dirname, 'pages');
const pageFiles = fs.readdirSync(pagesDirectory);


This will output an array of file names in the pages directory. Note that this will include all files, not just JavaScript files that are treated as pages by Next.js. To filter the list to only include JavaScript files, you can add a check for the file extension:

const pageFiles = fs.readdirSync(pagesDirectory).filter(file => file.endsWith('.js'));

Keep in mind that this code will only run on the server-side, so you’ll need to make sure it’s only executed during server-side rendering.