The Next.js build failed due to the absence of the required "slug" parameter being passed as a string

I'm currently working on setting up a blog using Next.js and TypeScript, and I've encountered an issue with [slug].tsx. The error message I'm receiving is:

Build error occurred Error: A required parameter (slug) was not provided as a string in getStaticPaths for /blog/[slug]

I've been following a tutorial closely, and you can find the specific timestamp here:
https://youtu.be/jJF6oBw1lbo?t=582

Initially, I had success in converting the tutorial from JavaScript to TypeScript until I ran into this particular issue which is now causing the build to fail.

When I attempt to run "yarn run dev", I encounter the following error:

TypeError: Cannot read property 'tap' of undefined

Below is the code snippet for [slug].tsx:

import { GetStaticPaths, GetStaticProps } from 'next'

let client = require('contentful').createClient({
    space: process.env.CONTENTFUL_SPACE_ID,
    accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
})

type Params = {
    params: {
        slug: string
    }
}

export const getStaticPaths: GetStaticPaths = async () => {
    let data = await client.getEntries({
        content_type: 'article',
    });
    return {
        paths: data.items.map(item => ({
            params: {slug: item.fields.slug},
        })),
        fallback: true,
    }
}

export const getStaticProps: GetStaticProps = async ({ params }) => {
    let data = await client.getEntries({
        content_type: 'article',
        'fields.slug': params.slug
    })
    return {
        props: {
            article: data.items[0]
        }
    }
}

export default function Article({ article }) {
    
    return <article>
        <h1>{article.fields.title}</h1>
        {article.fields.content}
    </article>

}

I suspect the issue might have to do with the data type of the slug. Should I explicitly define it as a string? And if so, how can I go about doing that?

Answer №1

To ensure compatibility with NextJS getStaticPaths, make sure that each property in the params object is a string. Any errors can be checked in the source code.

Confirm that the slug type is correctly defined (and utilized) as shown below:

type Params = {
    params: {
        slug: string
    }
}

When returning data from Contentful in the getStaticPaths function, be sure that the params.slug property is a string:

params: {slug: item.fields.slug},

Validate the slug property and ensure it is required as a string in your Contentful content model.

Handle cases where item.fields.slug may be undefined, typically occurring when drafts are auto-saved with empty required fields in Contentful.

Consider using optional chaining to safeguard the expression from any invalid references, for example: item?.fields?.slug. In this case, utilizing a simple OR logical operator is sufficient.

A concise solution for the getStaticPaths function could resemble the following:

const paths = data.items.reduce((pagePaths, item) => {
  const slug = item.fields.slug || '';

  if (slug.length > 0) {
    pagePaths.push({
      params: { slug },
    });
  }

  return pagePaths;
}, []);

return {
  paths,
  fallback: false,
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Vue.js: Overutilization of EventBus causing repeated function calls

I'm in the process of implementing an 'undo delete' feature. To achieve this, I am utilizing an Event Bus to broadcast an event to two separate components as shown below: Undo.vue: EventBus.$emit(`confirm-delete-${this.category}`, this.item ...

Generating dynamic div elements using jQuery

I am currently working on developing a button that will automatically generate pre-formatted divs each time it is clicked. The divs consist of forms with fields that should already be populated with data stored in JavaScript variables. Example: <d ...

How can I dynamically load a 3D model (in JSON format) at the current location of the mouse using Three.JS?

I'm currently working on a feature that involves loading a 3D model based on the mouse's position. Utilizing jQuery drag and drop functionality for this purpose has helped me load the model onto the canvas successfully, but I'm facing issues ...

Is there a way to assign a role to a user without requiring them to send a message beforehand?

I've been searching for a solution to this issue, but all I could find were instructions on how to assign a server role to someone who has interacted in some way. Is there a way to locate a specific user on a server and assign a role to them without ...

What is the best way to initiate actions once the form has been successfully processed?

Could someone assist me with creating a form that hides after submission and displays a thank you message instead? I've tried the code below, but it seems that the action isn't being executed once the form is submitted. It's as if the ' ...

Retrieve and modify the various elements belonging to a specific category

I'm currently developing a chrome extension and I need to access all elements of this specific type: https://i.stack.imgur.com/sDZSI.png I attempted the following but was unable to modify the CSS properties of these elements: const nodeList = documen ...

Load images sequentially in a slideshow gallery using JQuery, showing the next five pictures at a time instead of loading all at once

Recently, I've been developing a slideshow for educational materials and images. However, a concern was raised by a colleague regarding the loading time of slideshows with over 50 images. Is there a way to optimize the loading process by only displayi ...

Can you explain the purpose of the statement `var MyConstructor = function MyConstructor()`?

Can you explain the distinction between these two code snippets: var NodestrapGenerator = module.exports = function NodestrapGenerator() { yeoman.generators.Base.apply(this, arguments); // more code here }; and: var NodestrapGenerator = module.expor ...

The Art of JavaScript Module Patterns in Image Sliders

I'm diving into the world of JavaScript and decided to try my hand at creating an image slider. I managed to put together a basic version by following a couple of tutorials, and although it's working fine, I want to move it to an external js file ...

An error occurred with Next.js and Lottie where the property "completed" could not be added because the object

Encountering an issue with Lottie's animation. Attempting to retrieve a JSON file (Lottie Animation) from Contentful and display it using the Lottie Component. However, facing an error message: "TypeError: Cannot add property completed, the object is ...

What is the best method for linking an HTML file to CSS, javascript, and image files?

I need assistance with running an HTML file along with its source files that I downloaded from the server. The HTML file is located in NSCachesDirectory and here is the code snippet I am using. Can someone please help me figure this out? NSArray *paths ...

The For loop causing crashes in the Filter button functionality

I am currently working on implementing a buy it now only filter button for listings that allow that option. However, I am facing an issue where the app crashes when the button is clicked due to a for loop in my code. Strangely, if I remove the for loop, ...

Configuring environment variables in Next.js

I am currently in the process of configuring the ENV in Next.js Within next.config.js file const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin"); const withSass = require('@zeit/next-sass'); module.exports = withSass({ target: ...

Is there a way to ensure my chat view functions properly without relying on partial views?

I am currently working on integrating a private chat feature using SignalR in my project, and I have encountered an issue while creating a View with accessible model values to pass to the server. Specifically, I have a list of doctors, and when a user clic ...

Troubleshooting: Issues with Material-UI's Disabled attribute functionality

I am facing an issue with disabling the edit button after clicking on complete. I have tried passing the state in the disabled attribute, but it doesn't seem to work. I suspect it may be due to the asynchronous nature of setState. Additionally, when p ...

Converting this Jquery function to vanilla Javascript

I'm currently encountering difficulties reworking this slideshow feature using Javascript. Due to certain project limitations, I am required to switch back to pure JS. document.querySelectorAll(".fadein img:not(:first-child)").forEach(function(element ...

Displaying an element outside with reduced opacity using fabric js and controls placed above overlay

The property controlsAboveOverlay in Fabric.js is a boolean that, when set to true, will display the controls (borders, corners, etc.) of an object above the overlay image. The overlay image is an image that can be placed on top of the canvas. Currently, ...

The isAuthenticated status of the consumer remains unchanged even after being modified by a function within the AuthContext

I am working on updating the signout button in my navigation bar based on the user's authentication status. I am utilizing React Context to manage the isAuthenticated value. The AuthProvider component is wrapped in both layout.tsx and page.tsx (root f ...

Sidenav Content with all elements having opacity applied

How can I ensure that all page elements have a black background color when the mobile navigation is opened on the left screen, while ensuring that my sidebar and content image do not get overlaid by the black background? Here is my code: function openNav( ...

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...