Server-side rendering with Next.js API routes

Tutorial 4 of 5

1. Introduction

In this tutorial, our main goal is to equip you with the skills needed to perform server-side rendering with Next.js API routes. You will learn how to fetch data from the server-side and pass it to a component for rendering in Next.js.

By the end of this guide, you will be proficient in:
- Understanding the concept of server-side rendering in Next.js
- Creating API routes in Next.js
- Fetching data server-side in Next.js
- Passing the fetched data to a component for rendering.

Prerequisites:

You need to have a basic understanding of:
- JavaScript (ES6)
- React
- Node.js
- Basic knowledge of Next.js would be helpful, but not necessary.

2. Step-by-Step Guide

Understanding Server-Side Rendering (SSR) in Next.js:

Server-side rendering allows the server to pre-render a page's initial state, which can be directly sent to the client. This technique can improve performance and SEO. In Next.js, any file in the pages directory will become a route.

Creating API routes in Next.js:

Any file inside the pages/api directory is mapped to /api/* and will be treated as an API endpoint instead of a page. They are server-side only bundles and won't increase your client-side bundle size.

Fetching Data Server-Side in Next.js:

Next.js provides a function getServerSideProps which allows you to fetch data at request time. It is called server-side which means it's never run on the client-side and hence you can do direct database queries.

Passing the Fetched Data to a Component for Rendering:

The fetched data can be passed to the component by returning it from getServerSideProps as props.

3. Code Examples

Create a new Next.js app:

npx create-next-app@latest my-app

Create a new file inside the pages/api directory named users.js:

// pages/api/users.js
export default (req, res) => {
  res.status(200).json({ users: [{ name: 'John Doe' }] })
}

Create a new file inside the pages directory named index.js:

// pages/index.js
import fetch from 'node-fetch';

export async function getServerSideProps() {
  const res = await fetch(`http://localhost:3000/api/users`)
  const data = await res.json()

  return { props: { users: data.users } }
}

export default function Home({ users }) {
  return (
    <div>
      <h1>List of users</h1>
      {users.map(user => <p>{user.name}</p>)}
    </div>
  )
}

4. Summary

In this tutorial, we've learned about server-side rendering in Next.js, how to create API routes, how to fetch data server-side, and pass it to a component for rendering. You can extend this knowledge to fetch data from any API endpoints and render it on the server side.

For further learning, you can explore:
- Static Site Generation (SSG) in Next.js
- Client-side data fetching in Next.js
- Deploying Next.js applications.

5. Practice Exercises

  1. Create a new API route that returns a list of products.
  2. Fetch the list of products server-side and display them on a page.
  3. Fetch a single product server-side based on its id and display it on a page.

For further practice, you can try fetching data from a real API like the JSONPlaceholder API or the OpenWeather API.