0
votes

I currently have a file structure like so within the 'src' directory:

|____pages
| |____FirstPage
| | |____First.js
| | |____index.js
| |____SecondPage
| | |____Second.js
| | |____index.js
| |____FirstDynamicRoutePage
| | |____PageToRenderOnDynamicRoute.js
| | |____index.js

I would like to keep this file structure and use dynamic routing. For example, the route for 'PageToRenderOnDynamicRoute.js" will be something like '/page/pageType/:pageId/otherSlug/:slug'.

I am aware that I can use the dynamic routing provided by Next.js, but I do not want to use the necessary file structure of:

| |____page
| | |____pageType
| | | |____[pageId]
| | | | |____otherSlug
| | | | | |____[slug].js

I have tried using next-routes, but ran into many issues, including: returned 404 when using getStaticProps or getServerSideProps, returned 404 on refresh of page, returned 404 when url typed in manually.

Does anyone know of a way that I can keep my existing file structure AND use dynamic routing? I am open to any options, including continuing to try next-routes if you are aware of working solutions to the aforementioned issues. I appreciate your help!

1

1 Answers

0
votes

I have found an answer thanks to help from the Next.js chat, it was recommended to use the built-in rewrites feature provided by Next.js, here is how I implemented that in a nutshell:

  1. Updated to Next.js version 9.5.3
  2. Set up my next.config.js file like so:

const withSass = require('@zeit/next-sass')
const withTM = require('next-transpile-modules');
const withCSS = require("@zeit/next-css");
const withImages = require('next-images')

const myModule = module.exports = withImages(withSass(withCSS(withTM({
  transpileModules: ['react-bulma-components'],
  sassLoaderOptions: {
    includePaths: ["./src"]
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['css-loader'],
      },
    ],
  },
}))));

myModule.rewrites = async () => {
  return [
      { source: '/page/pageType/:slug*', destination: '/FirstDynamicRoutePage' },
  ];
};
  1. Make sure my custom server was using the Next.js handler as shown in their docs.
  2. Use next/link to add my dynamic link where I needed it:

   <Link href={`/page/pageType/${props.pageId}/otherSlug/${props.slug}`}>
        <a>
          {props.name}
        </a>
</Link>

That's it! Hopefully this answer can help others with the same question.