How to access route parameter inside getServerSideProps in Next.js?

You can access the route parameters through getServerSideProps‘s context, using the params field.

params: If this page uses a dynamic route, params contains the route parameters. If the page name is [id].js, then params will look like { id: ... }.

— Next.js, Data Fetching: getServerSideProps, Context parameter

export async function getServerSideProps(context) {
    const id = context.params.id // Get ID from slug `/book/1`
    
    // Rest of `getServerSideProps` code
}

Alternatively, you can also use the query field to access the route parameters. The difference is that query will also contain any query parameter passed in the URL.

export async function getServerSideProps(context) {
    const id = context.query.id // Get ID from slug `/book/1`
    // If routing to `/book/1?name=some-book`
    console.log(context.query) // Outputs: `{ id: '1', name: 'some-book' }`

    // ...
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)