Next.js is a React-based web framework that provides several features to help you build server-rendered React applications. Next.js has built-in support for server-side rendering (SSR), which means that you can pre-render your React components on the server and serve HTML pages to the client.
Here’s an example of a simple Next.js SSR application:
First, create a new Next.js project by running the following commands:
Next, create a new page in the pages
directory:
This page will be pre-rendered on the server and sent to the client as HTML. Now, start the development server with npm run dev
and navigate to http://localhost:3000
to see your app in action.
Next.js also provides a getServerSideProps
function that allows you to fetch data from an external API or database and pass it as props to your components. Here's an example:
This page fetches a list of users from the JSONPlaceholder API and passes it as props to the UsersPage
component. The getServerSideProps
function runs on the server and fetches the data before the page is rendered.
Finally, Next.js also provides a getInitialProps
function that can be used for server-side rendering as well as client-side rendering. Here's an example:
This page fetches a single post from the JSONPlaceholder API based on the id
parameter in the URL and passes it as props to the PostPage
component. The getInitialProps
function can run on the server or the client, depending on how the page is accessed.
I hope this helps you understand how to use SSR with Next.js!