Next JS nested routing

1.8k Views Asked by At
-component
---->sidebar.js
---->exampleTabOne.js
---->exampleTabTwo.js
---->exampleTabThree.js

--pages
---->setting(which include all sidebar and those exampletabs)

i do've above folder structure in my nextJS project. here as per nextjs doc

on localhost/setting i can easily view my page but what i want to achieve is something like below:

1.localhost/setting/exampleTabOne
2.localhost/setting/exampleTabTwo/EXAMPLEID
3.localhost/setting/exampleTabThree/EXAMPLEID#something#something 

the last part Url with # is something like inside tab content i ve another tabs so i want to fix it with Hash url so that while ssr i can easily open that inside tab too..

So, will you guys please suggest me how to solve this?

1

There are 1 best solutions below

0
On BEST ANSWER

Here , In Next JS, We can achieve this by defining in server.js file.

// This file doesn't go through babel or webpack transformation.
// Make sure the syntax and sources this file requires are compatible with the current node version you are running
// See https://github.com/zeit/next.js/issues/1245 for discussions on Universal Webpack or universal Babel
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer((req, res) => {
    // Be sure to pass `true` as the second argument to `url.parse`.
    // This tells it to parse the query portion of the URL.
    const parsedUrl = parse(req.url, true);
    const { pathname, query } = parsedUrl;

    if (pathname === '/setting/exampleTabOne') {
      app.render(req, res, '/setting', query);
    } else if (pathname === '/setting/exampleTabTwo/EXAMPLEID') {
      app.render(req, res, '/setting', query);
    } else {
      handle(req, res, parsedUrl);
    }
  }).listen(3000, err => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});

Where In setting page we can dynamically load the respective component watching url pathname.