0

I'm using dynamic routes and using fallback:true option to be able to accept newly created pages

first i check if parameters is true then i create related props and show the component with that props. In console i can also see that next.js create new json file for that related page to not go to server again for the next requests to the same page.

But even I type wrong address next create new json file for that path. It means that next.js create json file for every wrong path request.

How can avoid that vulnerable approach?

export const getStaticProps: GetStaticProps = async ({ params }) => {
  if (params.slug[0] === "validurl") {
    const { products } = await fetcher(xx);
    const { categories } = await fetcher(xx);
    return { props: { categories, products } };
  } else {
    return { props: {} };
  }
};

const Home = (props: any) => {
  if (!props) {
    return <div>404</div>;
  }
  return (
    <MainLayout {...props}>
      <FlowItems items={props.products} />
    </MainLayout>
  );
};
  • This should help https://github.com/vercel/next.js/discussions/10960 – de3 Sep 25 '20 at 23:06
  • it doesn't solve problem of creating empty .json fiiles for wrong url requests... – steppenwolf Sep 28 '20 at 12:03
  • Does this answer your question: [How to avoid "Loading" for nonexistent static pages Next.JS](https://stackoverflow.com/a/65789232/1870780)? You can return `{ notFound: true }` from `getStaticProps` when the URL is not valid. – juliomalves Nov 16 '21 at 23:48

1 Answers1

0
export async function getServerSideProps(context) {
  console.log(context.params.slug);
  ...

You are in Server Side inside this getServerSideProps and passing the context lets you dynamically catch whatever value it takes for whatever request.

Then you can check the data you want to load like:

const slug = context.params.slug;

const data = await fetch(`${host}/endpoint/${slug.join('/')}`);

so the request will be like 'localhost:3000/endpoint/foo/slug/test

Then you can deal with those slugs and it's data in a backend logic (where it should be) in your endpoint (just to clarify this sort of logic it usually belongs to a gateway and not to an endpoint, this is just for educational purposes).

If the endpoint/gateway returns a 404 - Not found you can simply redirect to the 404.js page (which can be static), same for the rest of the possible errors available in your backend.

Joel Bonet
  • 91
  • 5