getStaticPaths throws "TypeError: segment.replace is not a function"

Viewed 1320

I'm new to Next.js's getStaticPaths and am now getting this error, having no clue what to do with it.

This is my code (I'm using query from serverless-mysql):

export async function getStaticPaths() {
    const userIds = await query(/* sql */`
          SELECT userId FROM user_table_v3test
      `);
    const mappedIds = JSON.parse(JSON.stringify(userIds.map(id => ({ params: { slug: [id.userId]}}))));

    return {
        paths: [
            { params: { slug: [] } },
            ...mappedIds
        ],
        fallback: false
    };
}

This returns in this error (on every page):

Server Error
TypeError: segment.replace is not a function

This error happened while generating the page. Any console logs will be displayed in the terminal window.

In my console the log is as follows:

Uncaught     at escapePathDelimiters (file://C:\Users\robbert.olierook\Documents\pom_v1\node_modules\next\dist\next-server\lib\router\utils\escape-path-delimiters.js:2:55)
    at Array.map (<anonymous>)
    at <unknown> (file://C:\Users\robbert.olierook\Documents\pom_v1\node_modules\next\dist\build\utils.js:21:1117)
    at Array.forEach (<anonymous>)
    at <unknown> (file://C:\Users\robbert.olierook\Documents\pom_v1\node_modules\next\dist\build\utils.js:21:502)
    at Array.forEach (<anonymous>)
    at buildStaticPaths (file://C:\Users\robbert.olierook\Documents\pom_v1\node_modules\next\dist\build\utils.js:17:1252)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

I have tried a couple of things.

The reason I wrapped my mappedIds in the silly parse/stringify construction is because of this issue: https://github.com/vercel/next.js/issues/11993.

Which appears to have been necessary, because when I omit the mappedIds with all the logic from getStaticPaths, and use the same logic in getStaticProps so I can pass mappedIds as a prop, I need to wrap the object in the parse/stringify construction or else it won't work.

Furthermore, once this worked, this allowed me to console.log the object to see what's going on. The result is this:

logged object of mappedIds

Which appears to be just formatted in the way I would need it in getStaticPaths.

Does anyone have any idea what is happening behind the surface (and more importantly, how to fix it)?

1 Answers

The values in your slug arrays need to be strings. Having numbers is what's triggering the error.

const mappedIds = userIds.map(id => ({ 
    params: { slug: [`${id.userId}`] }
}));
Related