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.
You need to have a basic understanding of:
- JavaScript (ES6)
- React
- Node.js
- Basic knowledge of Next.js would be helpful, but not necessary.
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.
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.
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.
The fetched data can be passed to the component by returning it from getServerSideProps
as props.
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>
)
}
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.
For further practice, you can try fetching data from a real API like the JSONPlaceholder API or the OpenWeather API.