Next.js: Extracting URL params inside getStaticProps function

Updated: January 9, 2023 By: Khue Post a comment

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

{ id: /* something */ }

You can get URL params from inside your getStaticProps or getServerSideProps function with the context argument (so that you can fetch data or do other logic on the server side with the params).

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 it, my friend. If you see something wrong, please comment. Happy coding and have a nice day