How can I use "useRouter" to get params in the url inside getServerSideProps() in Next.js

Issue

I want to get the URL params in the getServerSideProps() function. Here’s my code.

The purpose of my code is to take the params from the URL and fetch the API and display the output on the frontend.

import { useRouter } from 'next/router'
import connectMongo from '../../utils/connectMongoos';
import Post from '../../models/postModel';
import MarkdownComponent from '../../components/utils/markdown';

export const getServerSideProps = async () => {
  try {
    console.log('CONNECTING TO MONGO');
    await connectMongo();
    console.log('CONNECTED TO MONGO');

    console.log('FETCHING DOCUMENTS');
    // find the post with the slug that matches the slug in the url
    const post = await Post.findOne({ slug: router.query.slug }); // error comes here
    console.log('FETCHED DOCUMENTS');

    return {
      props: {
        data: JSON.parse(JSON.stringify(post)),
      },
    };
  } catch (error) {
    console.log(error);
    return {
      notFound: true,
    };
  }
};

export default function Posts({data}) {
  const router = useRouter()
  // const { slug } = router.query
  return(
    <div className="max-w-screen-md mx-auto font-inter m-2 p-4">
      <MarkdownComponent text={data.markdown} />
    </div>
  )
}

Here’s the error that I am encountering,

ReferenceError: router is not defined
    at getServerSideProps (webpack-internal:///./pages/post/[slug].js:26:19)
    at runMicrotasks (<anonymous>)

Solution

As per the NextJs 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: … }.

query: An object representing the query string.


     export async function getServerSideProps(context) {
        const slug = context.params // `Get the router query or slug here`
        
        // Rest of `getServerSideProps` code
    }

Answered By – Saurabh

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.