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

Viewed 12697

I want to query my Supabase table using the ID in the slug e.g. localhost:3000/book/1 then show information about that book on the page in Next.js.

Table

enter image description here

book/[id].js

import { useRouter } from 'next/router'
import { getBook } from '@/utils/supabase-client';

export default function Book({bookJson}) {
  const router = useRouter()
  const { id } = router.query
  
  return <div>
    <p>Book: {id}</p>
    <h1>{bookJson}</h1>
  </div>
}

export async function getServerSideProps(query) {
  const id = 1 // Get ID from slug
  const book = await getBook(id);
  const bookJson = JSON.stringify(book)

  return {
    props: {
      bookJson
    }
  };
}

utils/supabase-client.js

export const getBook = async (id) => {
  const bookString = id
  let bookId = parseInt(bookString);
  
  const { data, error } = await supabase
    .from('books')
    .select('id, name')
    .eq('id', bookId)

  if (error) {
    console.log(error.message);
    throw error;
  }

  return data || [];
};
1 Answers

As described in getServerSideProps documentation, you can access the route parameters through the 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: ... }.

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' }`

    // ...
}
Related