My personal website is built on Next.js and uses both the getStaticProps and getStaticPaths functions to dynamically generate the /blog/ and /portfolio/ pages at build time. While updating both methods to use their proper TypeScript types, following the documentation, I ran into an error when reading the parameter that I was passing from getStaticPaths into getStaticProps.

The error that appeared was:

Property ‘slug’ does not exist on type ‘ParsedUrlQuery | undefined’

After doing some research and finding a discussion on the Next.js GitHub regarding this issue, I recognised it was a gap in their documentation. It explains how to add the type to getStaticProps when used on its own but it doesn’t demonstrate how to access the property you’ve declared in getStaticPaths.


Background

getStaticPropsandgetStaticPaths are two methods that can be used for data fetching in Next.js. Briefly speaking getStaticProps lets you fetch data at build time and getStaticPaths enables you to specify dynamic routes to pre-render pages based on data.

For more information on these functions, read my post on different ways to fetch data in Next.js.

#next #typescript #javascript #react

Using getStaticProps and getStaticPaths with TypeScript - Next.js
9.90 GEEK