Search code examples
next.jscontentfulgetstaticpaths

How to Preserve Slashes in Contentful Slugs with Next.js


I am using Contentful and Next.js in my project. The slugs I receive from Contentful contain slashes (e.g., news-insights/blogname). However, when I fetch these slugs and try to build the pages, the slashes are encoded as %2F.

Here is my code:

// src/pages/[slug].jsx
export const getStaticPaths = async () => {
  const response = await client.getEntries({
    content_type: "blog",
    locale: "nl",
  });

  const paths = response.items.map((item) => {
    return {
      params: { slug: item.fields.slug },
    };
  });

  return {
    paths,
    fallback: true,
  };
};

How can I keep the slashes ( / ) in the slugs so that news-insights%2Fblogname remains news-insights/blogname?

Thank you for your help.

The slug from Contentful becomes news-insights%2Fblogname instead of news-insights/blogname. I tried to use:

params: { slug: ['news-insights', 'blogname'] }

but this did not work either. I was expecting the slashes to be preserved in the URL structure so that the pages could be properly generated and accessed as news-insights/blogname.


Solution

  • I have found the solution:

    Create a [...slug].jsx file and add here

    export const getStaticPaths = async () => {
      const response = await client.getEntries({
        content_type: 'blog',
        locale: 'nl',
      });
    
      const paths = response.items.map((item) => ({
        params: { slug: item.fields.slug.split('/') },
      }));
    
      return {
        paths,
        fallback: true,
      };
    };
    

    Thank you