Blog>
Snippets

Fetching Data at Request Time with API Routes

Create an API route to handle data fetching from a backend and use it within a Next.js page by making a server-side request.
// pages/api/data.js
export default async function handler(req, res) {
  // Simulate fetching data from a backend datasource
  const data = await fetchDataFromBackend();
  res.status(200).json(data);
}
This is an API route in Next.js, located in 'pages/api/data.js'. When a request is made to this endpoint, the handler function is called. This function simulates fetching data from a backend source by calling 'fetchDataFromBackend' (a placeholder for real data-fetching logic) and then sends the retrieved data back as a JSON response.
// pages/server-side.js
import React from 'react';

export async function getServerSideProps(context) {
  // Fetch data from the internal API endpoint
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/data`);
  const data = await res.json();

  // Pass data to the page via props
  return { props: { data } };
}

function ServerSidePage({ data }) {
  // Render data on the page
  return (
    <div>
      <h1>Data fetched at request time</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default ServerSidePage;
This code shows a server-side rendered Next.js page which resides in 'pages/server-side.js'. It makes use of 'getServerSideProps' to fetch data from the API endpoint we defined earlier. The data is fetched at request time, meaning it is always up-to-date when the page is rendered. The fetched data is then passed to the 'ServerSidePage' component and displayed in a nicely formatted JSON.