This guide will teach you how to call any REST API from your Next.js application. If you already have an existing API that you want to use, you can skip the first step, in which we create a fake REST API using Mockoon.
When working on your Next.js application, you may need to mock an API that doesn't exists yet, or is only partially available (see partial mocking with the proxy mode). For this, the easiest way is to create a mock API using a tool like Mockoon. (Read more about the benefits of API mocking).
To learn more about how to set up your first mock API with Mockoon, head over to the Getting started tutorial.
For the rest of the tutorial, we will use an array of fake blog posts. In Mockoon, create a
GET /posts API endpoint that returns an array of blog posts:
You can use the following JSON as the body returned by the endpoint:
Note that your fake mock server will be available at the following URL:
http://localhost:3000. This is the URL we will need to use in our Next.js page.
After creating a mock REST API endpoint in Mockoon, you can now call it from your Next.js page.
To do so, we need to use either the
getStaticProps or the
getServerSideProps functions. You can read more about these functions in the official documentation.
getStaticProps function will allow you to pre-render the page at build time using the props returned by
To fetch our blog posts from the mock API, we can use the
fetch function and add the resulting data in the returned props:
We can now render our blog posts on the page as
<li> using a simple
To avoid modifying the server URL directly in the Next.js page's code, you can put this URL in Next.js's environment variables.
To do so, create an environment variable in your
You can then use the environment variable exposed by Next.js through the
process.env object in the