Prevent the creation of routes from components and public folders in the pages folder. And deny access to see files in public folders. NextJs

Viewed 1184

I have NextJs application with a custom server where I have customized a route. Where I show the template depending on the hostname and pathname.

My server.js

const next = require('next');
const { createServer } = require('http');
const { parse } = require('url');
const dev = process.env.ENV === 'local';
const app = next({ dev });
const handle = app.getRequestHandler();

const port = 3000;

app.prepare().then(() => {
  createServer(async (req, res) => {
    const parsedUrl = parse(req.url, true);
    const { pathname, query } = parsedUrl;

    const pathnameFromServer = 'test_path_name';
    const templateFromServer = 'template1';

    if (pathname === `/${pathnameFromServer}`) {
      await app.render(req, res, `/${templateFromServer}`, query);
    } else {
      await handle(req, res, parsedUrl);
    }
  }).listen(port, (err) => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});

I am creating a template in the pages folder. And I want to create the components, public folder in it. Like this.

enter image description here

But NextJs build everything in the pages folder as routes.

My next.config.js

const withTM = require('next-transpile-modules')(['@nfs-react/components']);

module.exports = withTM({
  useFileSystemPublicRoutes: false,
});

I need to prevent the creation of routes from components and public folders in the pages folder. I also need to deny access to see files in public folders.

1 Answers

You can name the /pages folder something else, so Next.js will ignore it.

Related