Skip to content

Instantly share code, notes, and snippets.

@m-ripper
Last active July 13, 2021 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-ripper/971e59320660f95bc2246e98363177a1 to your computer and use it in GitHub Desktop.
Save m-ripper/971e59320660f95bc2246e98363177a1 to your computer and use it in GitHub Desktop.
Custom Next pages directory

Custom Next pages directory

Next.js has a limited set of possible pages-directories, either pages or src/pages. This is not going to change in the future, as mentioned here.

In some cases it is necessary or helpful to have a custom pages-directory.

These two snippets make it possible:

patch-custom-next-pages-dir.js

Monkey-patches findPagesDir inside of next to check for the custom pages-directory at RELATIVE_CUSTOM_PAGES_PATH.

package.json

Provides a custom next command which automatically requires the patch-custom-next-pages-dir.js-file before calling the Next.js-CLI.

{
"scripts": {
"next": "node -r ./patch-custom-next-pages-dir.js ./node_modules/next/dist/bin/next",
"dev": "npm run next",
"build": "npm run next build",
"start": "npm run next start"
}
}
const { join } = require('path');
const findPagesDir = require('next/dist/lib/find-pages-dir');
const RELATIVE_CUSTOM_PAGES_PATH = 'src/client/pages';
function isPatched() {
return !!findPagesDir.__isPatched;
}
function patchCustomNextPagesDir() {
const originalFindPagesDir = findPagesDir.findPagesDir;
findPagesDir.findPagesDir = function (dir) {
try {
return originalFindPagesDir(dir);
} catch (e) {
const pagesDir = join(dir, RELATIVE_CUSTOM_PAGES_PATH);
if (findPagesDir.existsSync(pagesDir)) {
return pagesDir;
}
throw e;
}
};
findPagesDir.__isPatched = true;
}
if (!isPatched()) {
patchCustomNextPagesDir();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment