Next.js: Extracting URL params inside getStaticProps function

Last updated on May 21, 2022 A Goodman Loading... Post a comment

In Next.js, If a page uses a dynamic route, params contain the route parameters. For instance, If the page name is [id].js, then params will look as follows:

{ id: /* something */ }

You can get URL params from inside your getStaticProps or getServerSideProps function with the context argument.

Here’s an example with getStaticProps:

// pages/[id].js

export async function getStaticProps(context) {
    const { params } = context;
    const id = params.id;

    const data = /* Fetching data with the id */

    return {
        props: data,
    }
}

You can do the same with getServerSideProps:

// pages/[id].js

export async function getServerSideProps(context) {
    const { params } = context;
    const id = params.id;

    /* ... */
}

That’s if. Further reading:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like