reactjsnext.jsnextjs14

How to use dynamic routes on static NextJs app


I need the /out folder from NextJs to be able to deploy it. The issue is that I have used dynamic routes witch aperantlly are SSR and I am trying to make them CSR.

Right now I have app/(pages)/projects/[id]/page and this is the code

import { projects } from '@/data/projects';
import SingleProjectPage from '@/components/SingleProjectPage';

export const generateStaticParams = async () => {
  return projects.map((project) => ({
    id: project.id.toString(),
  }));
};

const getProject = async (id: string) => {
  return projects.find((p) => p.id === id) ?? null;
};

const Project = async ({ params }: { params: { id: string } }) => {
  const project = await getProject(params.id);

  if (!project) {
    return (
      <div className='w-full h-[100vh] flex justify-center items-center text-5xl font-bold'>
        Project <span className='text-primary mx-2'>not</span> found
      </div>
    );
  }

  return <SingleProjectPage project={project} />;
};

export default Project;

When I run npm run build I get this:

└ ● /projects/[id]                       3.35 kB         144 kB
    ├ /projects/1
    ├ /projects/2
    ├ /projects/3
    └ /projects/4
+ First Load JS shared by all            87.2 kB
  ├ chunks/117-057d17d2e788cd74.js       31.6 kB
  ├ chunks/fd9d1056-f1963c9e20a75983.js  53.7 kB
  └ other shared chunks (total)          1.9 kB

Is there a solution for this?

also, I did added output: 'export' to next.config.mts


Solution

  • If anyone else encounters the same issue, to fix it, add the following line to the package.json: ' type": "module", under version or name.

    Also, next.config.js needs to be either .js or mjs; ts or mts won't work.

    After all of this, you still need to use the code from the question to generate the static pages using the function generateStaticParams. It needs to be named generateStaticParams.

    Also, instead of using the nextjs dynamic routes with [slug] I think it's better to just use query like in the answer from @Yahya Aghdam