Gone are the days when you had to create a separate backend for your website.
Next.js is a React meta-framework with features that simplify the process of building production-ready web apps.
It installs the necessary packages and files to get you started with building a Next.js program.
Run this command in a terminal to create a new Next.js folder called api-routes.
You may receive a prompt to install create-next-app.
When the command finishes, fire up the api-routes folder to start creating the API routes.
In Next.js, you must create API routes inside the /pages/api folder.
Next.js generates API endpoints for each of the files in this folder.
If you add user.js to /pages/api, Next.js will create an endpoint at http://localhost:3000/api/user.
A basic Next.js API route has the following syntax.
You must export the handler function for it to work.
Mocking the Todo Database
To get the todos, you must create a GET endpoint.
Create the todo items in todo.js in the root folder of your software then add the following data.
These todo items are from the DummyJSON website, aREST APIfor mock data.
you might find the exact data from thisDummyJSON todos endpoint.
Next, create the API route in/pages/api/todos.jsand add the handler function.
This route handles the GET and POST endpoints.
For other methods, the handler returns an error.
To consume the API, create a function called fetchTodos that retrieves data from the API endpoint.
The function uses the fetch method but you’re able to alsouse Axios to make API requests.
Then call this function when you click a button.
The list in this snippet displays the todo items when they are fetched.
For the POST endpoint, create a new function called saveTodo that makes a POST request to the API.
The saveTodo function then stores them in the todos state.
Then, create a form with a text input bar to receive the new todo item.
The submit handler function of this form will call the saveTodo function.
The handler adds a new todo to the database every time a user submits the form.
Now you’re free to create a full stack system without leaving your Next.js project folder.
API routing is one of the many benefits that Next.js provides.
Next.js also offers performance optimizations such as code splitting, lazy loading, and built-in CSS support.
If you are building a website that needs to be fast and SEO friendly, you should consider Next.js.