0
import { ClientOnly } from './client';
import '../../assets/main.scss';
 
export function generateStaticParams() {
  return [{ slug: [""] }]
}
 
// Default component
export default function Page() {
  return <ClientOnly />;
}

I migrate react.js project into Next.js by referring steps from docs of next.js about migration this is code inside src/app/[[...slug]]/page.js

In this code i am giving static slug which is by default for home page, my project have a admin panel through which i can create a new pages i don't have backend or frontend code of admin panel because it is a CMS type system i am only having with the frontend code of user panel which i am converting in next.js for SEO purpose when i create n new pages every new page has its own unique slug

now the problem is this code only allowing me to go the static slugs like if i want to go to clients page i need to change return [{ slug: ["client"] }] like this

but there are approx 200 pages and there slugs are unknown and new page are going to add it everyday so its obvious i cant put each and every slug statically

so i want to make this code dynamic to take the any slug and if the page with that slug is not in database then 404 page should appear

1 Answer 1

0
generateStaticParams

Every slug you put in this function is generated statically in the build time(unless you put revalidation on the server component).

Now, if any new slug comes to this server component, generate a static page for that slug. You do not need to put every slug on the function, but if you wanna cache static pages in the build time, fetch all slugs from API/DB and return it.

For the 404 problem, you can use the notFound helper in the server component when the slug is not found.

ex.

import { notFound } from "next/navigation";

export const dynamicParams = true;

export async function generateStaticParams() {
  return [{ slug: "1" }, { slug: "2" }];
}

async function getPost(params: { slug: string }) {
  return await new Promise<{ id: number; title: string } | false>((resolve) => {
    setTimeout(function () {
      const id = Number(params.slug);
      if (isNaN(id) || !id || ![1, 2].includes(id)) resolve(false);
      else resolve({ id: id, title: "this is title" });
    }, 500);
  });
}

export default async function Post({ params }: { params: { slug: string } }) {
  const post = await getPost(params);
  if (!post) return notFound();

  return (
    <div>
      {post.title} for {post.id}
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.