How to Access Route Parameter Inside getServerSideProps in Next.js?

getServerSideProps in NextJS is used for server-side rendering (SSR) of a page. When a user accesses a page that uses getServerSideProps, NextJS calls this function on the server every time the page is requested. This means that the page content is generated dynamically on each request, allowing you to fetch data from an external API, or a database, or perform any server-side logic before sending the HTML response to the client.

Key Reasons to use getServerSideProps

  • Dynamic Data Fetching: If your page content depends on dynamic data that changes frequently or is specific to each request (like user-specific data), getServerSideProps allows you to fetch this data at runtime and render the page with the updated information.
  • SEO Optimization: Server-side rendering is beneficial for SEO because search engine crawlers can index fully rendered HTML content, including dynamically generated content fetched via getServerSideProps. This improves the visibility of your website’s content in search engine results.
  • Authentication and Authorization: Since getServerSideProps runs on the server, you can perform authentication and authorization checks securely before rendering the page. This ensures that sensitive data or restricted content is only displayed to authorized users.
  • Server-Side Logic: If your page requires server-side computations, data processing, or interaction with server-side APIs, getServerSideProps allows you to execute this logic on the server before sending the page to the client, optimizing performance and security.

Steps to Setup a NextJS App

Step 1: Create a NextJS application using the following command and answer a few questions.

npx create-next-app@12 my-next-app

Step 2: It will ask you some questions, so choose as the following.

√ Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? ... Yes
√ Would you like to customize the default import alias (@/*)? ... No

Step 3: After creating your project folder, move to it using the following command.

cd app_name

Step 4: Create [Id].js file in the pages folder.

Project Structure:

After adding [id].js file

Example: Below is an example to accessing route parameter inside getServerSideProps in NextJS.

JavaScript
// src/pages/[id].js

export default function Page({ data, error }) {
    if (error) {
        return (
            <main>
                <div style={{ fontSize: '20px', color: 'red' }}>{error}</div>
            </main>
        );
    }

    let description = "";
    if (data && data.description) {
        description = data.description;
    }

    return (
        <main>
            <div style={{ fontSize: '40px' }}>{description}</div>
        </main>
    );
}

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

    try {
        const res = await fetch(
            `https://api.sampleapis.com/codingresources/codingResources/${id}`);

        if (!res.ok) {
            throw new Error('Failed to fetch data');
        }

        const data = await res.json();
        return {
            props: {
                data,
            },
        };
    } catch (error) {
        return {
            props: {
                error: error.message,
            },
        };
    }
}

Start your NextJS app using the below command:

npm run dev  

Output: You can check the output by visiting this link: http://localhost:3000/{id}.

Output



Contact Us