Introduction
Modern web applications are usually built using a frontend framework and backend API. A common combination is using Next.js for the frontend and FastAPI for the backend.
Next.js is a powerful React framework used to build fast and interactive user interfaces, while FastAPI is a modern Python framework designed for building high performance APIs.
However, many developers struggle when trying to connect a Next.js frontend to a FastAPI backend.
In this beginner-friendly tutorial, you will build a beginner-friendly Next.js and FastAPI project and learn step-by-step how to connect Next.js to a FastAPI backend, fetch data from the API, and display it in your frontend application.
Table of Contents
- Prerequisites
- Project Overview
- Setting Up the FastAPI Backend
- Creating a Simple API Endpoint
- Setting Up the Next.js Frontend
- Fetching Data from FastAPI in Next.js
- Handling CORS Between Next.js and FastAPI
- Common Errors and Fixes
- Conclusion
Prerequisites
Before starting this tutorial, make sure you have the following:
- Python 3.9 or later installed
- Node.js and npm installed
- Basic knowledge of Python
- Basic knowledge of React and Next.js
- Basic understanding of REST APIs
- A code editor such as VS Code
In this tutorial we will build a simple full stack application where:
- The FastAPI backend provides an API endpoint
- The Next.js frontend fetches data from that API
- The data is displayed in the user interface
Project Overview
In this tutorial,we will build a simple full stack application using Next.js for the frontend and FastAPI for the backend.
The FastAPI backend will expose an API endpoint that returns a list of users in JSON format. The Next.js frontend will send a request to this API, receive the data, and display it in the user interface.
This simple example will help you understand the core concept of connecting the frontend application to a backend API.
How the Application Works
The application flow will look like this:
Next.js (Frontend)
↓
Fetch API Request
↓
FastAPI (Backend)
↓
JSON Response
↓
Display Data in the UIStep-by-step Flow:
- The user opens the Next.js Application in the browser.
- The frontend sends a request to the FastAPI API endpoint.
- FastAPI processes the request and returns data in JSON format.
- Next.js receives the response.
- The data is rendered in the user interface.
Now that you have understood the application flow, let’s set up the FastAPI backend.
Setting up the FastAPI Backend
In this section, we will create the FastAPI backend that will provide an API endpoint for our Next.js frontend.
We will:
- Create a backend project folder
- Create a virtual environment
- Install FastAPI and required dependencies
- Write a simple FastAPI application
- Run the development server
Step 1 – Create the Backend Project Folder
First, create a folder for the backend project.
mkdir fastapi-backend
cd fastapi-backendThis folder will contain all the backend code for the API.
Step 2 – Create a Virtual Environment
A virtual environment keeps your project dependencies isolated from other python projects.
Create the virtual environment:
python -m venv venvActivate the virtual environment:
Mac/Linux:
source venv/bin/activateWindows:
venv\Scripts\activateAfter activation you should see (venv) in your terminal.
Step 3 – Install Required Packages
Now install the required backend packages.
pip install fastapi uvicornThese packages serves different purposes:
- FastAPI – used to build the backend API
- Uvicorn – an ASGI server used to run the FastAPI applications
Step 4 – Create the FastAPI Application File
Create a file called main.py
touch main.pyNow open the file and add the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "FastAPI backend is running"}This code creates a simple FastAPI application with one API endpoint.
Step 5 – Run the FastAPI Server
Start the development server using Uvicorn.
uvicorn main:app --reloadExplanation of the command:
main– the python file nameapp– the FastAPI instance--reload– automatically reload the server when code changes
Step 6 – Test the Backend
Open the browser and visit:
http://127.0.0.1:8000You should see the following responses:
{
"message": "FastAPI backend is running"
}FastAPI also automatically generates interactive API documentation.
Open:
http://127.0.0.1:8000/docsThis page provides an interactive interface to test your API endpoints.
Now that our FastAPI backend is running successfully, we can create the API endpoint that the Next.js frontend will consume.
Creating a Simple API Endpoint
In the previous section, we created a simple FastAPI application and started the development server.
Now we will create a new API endpoint that returns a list of users. This endpoint will later be called from the Next.js frontend.
Step 1 – Define Sample Data
For simplicity, we will use a small list of stored users stored in memory. In a real application, the data usually come from a database.
If you want to learn how to build a database-powered API using FastAPI and SQLAlchemy, you can read our previous tutorial:
FastAPI + SQLAlchemy Tutorial: Build a CRUD API Step-by-Step
In this tutorial, however, we will keep the backend simple so we can focus on connecting the Next.js frontend to the FastAPI API.
Open the main.py file and update the code.
from fastapi import FastAPI
app = FastAPI()
users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
{"id": 3, "name":
Step 2 – Understanding the Endpoint
The new route we created is:
GET /usersThis endpoint returns a list of users in JSON format.
Step 3 – Test the Endpoint If the server is already running, FastAPI will automatically reload the application.
Open the following URL in your browser:
http://127.0.0.1:8000/usersYou should see a response similar to this:
[
{
"id": 1,
"name": "Alice"
},
{
"id": 2,
"name": "Bob"
},
{
"id": 3,
"name": "Charlie"
}
]Step 4 – Test Using the Interactive Docs
FastAPI automatically generates API documentation using Swagger UI.
Open:
http://127.0.0.1:8000/docsFind the /user endpoint and click on Try it out. This allows you to test the API directly from the browser.
At this point, our backend API is ready. The next step is to create the Next.js frontend that will request data from this endpoint and display it in the user interface.
Setting up the Next.js Frontend
In this section, we will create the Next.js frontend application that will request data from our FastAPI backend.
We will:
- Create a new Next.js project
- Install the required dependencies
- Run the development server
- Understand the basic project structure
Step 1 – Create the Next.js Project
Open a new terminal and run the following command.
npx create-next-app@latest nextjs-frontendFollow the setup prompt. You can choose the default options or configure the project according to your own preferences.
Then navigate to the project folder.
cd nextjs-frontendStep 2 – Start the Development Server
Run the following command to start the development server:
npm run devOnce the server start, open your browser and visit:
http://localhost:3000You should see the default Next.js welcome page.
Step 3 – Understanding the Project Structure
After creating the project, you folder structure will look similar to this:
nextjs-frontend
│
├── app
│ └── page.js
│
├── public
│
├── package.json
└── next.config.js Important Folders:
- app/ — contains the pages and UI components
- public/ — used for static assets such as images
- package.json — contains project dependencies and scripts
Step 4 – Editing the Main Page
Open the file:
app/page.jsReplace the existing code with a simple placeholder UI.
export default function Home() {
return (
<main>
<h1>User List</h1>
<p>Users will appear here after fetching data from the FastAPI backend.</p>
</main>
);
}Save the file and refresh the browser.
You should now see a simple page with the title User List.
This page will later display the data we fetch from the FastAPI backend.
Fetching Data from FastAPI in Next.js
Now that our FastAPI backend and Next.js frontend are running, we can connect them.
The goal is simple:
- The Next.js frontend sends a request to the FastAPI API.
- FastAPI returns a list of users.
- The frontend displays the users on the page.
Step 1 – Understanding the API Endpoint
In the previous section, we created the following API endpoint:
GET/users
This endpoint is avaialble at:
http://127.0.0.1:8000/usersWhen called, it returns a JSON response like this:
[
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" },
{ "id": 3, "name": "Charlie" }
]Next.js will fetch this data and render it in the UI.
Step 2 – Update the Home Page
Open the following file:
app/page.jsReplace the code with the following:
"use client";
import { useEffect, useState } from "react";
export default function Home() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("http://127.0.0.1:8000/users")
.then
Let's break down what this code does:
useState([])creates a state variable to store the usersuseEffect()runs when the component loadsfetch()function sends a request to the FastAPI API- The API returns JSON data.
setUsers(data)stores the data in state.- The
map()function renders the users in the UI.
Step 3 – Test the Integration
Make sure both servers are running.
FastAPI server:
uvicorn main:app --reloadNext.js server:
npm run devOpen the frontend in your browser:
http://localhost:3000If everything is working correctly, you should see a list of users displayed on the page.
At this point, Next.js is successfully communicating with the FastAPI backend.
Handling CORS between Next.js and FastAPI
When the frontend and backend runs on different ports, the browser may block request due to the Cross-Origin Resource Sharing (CORS) policy.
For example:
- Next.js runs on
http://localhost:3000- FastAPI runs on
http://localhost:8000Since these are different origins, the browser blocks the requests for security reasons.
To allow the frontend to communicate with the backend, we need to enable CORS in the FastAPI application.
Step 1 – Import the CORDMiddleware
Open the main.py file and add the following import.
from fastapi.middleware.cors import CORSMiddlewareStep 2 – Configure CORS
Add the following configuration after creating the FastAPI app:
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)Your main.py should now look similar to this:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
Step 3 – Restart the Server
After adding the middleware, restart the FastAPI server:
python main:app –reloadNow the backend allows incoming requests from the Next.js frontend.
Step 4 – Test the Connection Again
Make sure both servers are running.
- FastAPI
uvicorn main:app --reload- Next.js
npm run devOpen the frontend again:
http://localhost:3000The user list should now load successfully without any CORS error.
Why CORS is Important
CORS protects users by preventing unauthorized websites from accessing APIs. By configuring it correctly, we allow only trusted origins such as our frontend to communicate with the backend.
To learn more about CORS and CORS errors, you can read our guide on How to Fix CORS issues in FastAPI Step-by-Step
Common Errors and Fixes
When connecting a Next.js frontend to a FastAPI backend, developers often run into a few common problems. Below are some typical errors and how to fix them.
1. CORS Error
One of the most common issues is a CORS error in the browser console.
Example Error Message:
Access to fetch at 'http://127.0.0.1:8000/users' from origin 'http://localhost:3000' has been blocked by CORS policy.Cause: The frontend and backend are running on different origins:
- Frontend —
http:\\localhost:3000 - Backend —
http:\\localhost:8000
Browsers block cross-origins requests unless the backend explicitly allows them.
Solution: Enable CORS in the FastAPI application:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)Restart the FastAPI server after making this change.
2.Network Error When Fetching the API
Sometimes the frontend cannot reach the backend.
Example Error:
TypeError: Failed to fetchPossible Causes:
- The FastAPI server is not running
- The API URL is incorrect
- The port number is wrong
Solution: Make sure the FastAPI is running:
uvicorn main:app –reloadThen verify the API works by opening the URL in your browser:
http://127.0.0.1:8000/usersIf the API works in the browser, the frontend should be able to fetch it.
3. API Returns Empty Data
Sometimes the frontend loads but shows no users.
Possible Cause: The API response might be empty or incorrect.
Solution:
Check the /user endpoint in the FastAPI backend.
users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
{"id": 3, "name": "Charlie"}
]Also check the browser console to see if there are any errors.
4. Forgetting ”use client” in Next.js
In modern Next.js applications, components inside the app directory are server components by default.
If you use React hooks like useState or useEffect you must enable client side rendering.
Solution:
Add this line at the top of your component file:
"use client";Without this directive, React hooks will not work.
These fixes resolve most issues developers encounter when connecting a Next.js frontend with a FastAPI backend.
Conclusion
In this tutorial, we learned how to connect a Next.js frontend to a FastAPI backend and build a simple full stack application.
We started by setting up a FastAPI backend and creating an API endpoint that returns a list of users. Then we created a Next.js frontend application and used the fetch() function to request data from the API.
We also enabled CORS in the FastAPI backend to allow communication between the frontend and the backend running on different ports.
By the end of this tutorial, you learned how the backend and frontend communicate in a full stack architecture:
Next.js (Frontend)
↓
API Request (fetch)
↓
FastAPI (Backend)
↓
JSON Response
↓
Data Rendered in the UIUnderstanding this communication flow is an important step in building modern web applications.
Next Step
Now that you know how to connect a frontend to a backend API, you can extend this project by:
- Connecting FastAPI to a real database such as PostgresSQL
- Creating POST, PUT, and DELETE endpoints
- Adding form inputs in Next.js to create new users.
- Implementing authentication with JWT. If you want to learn how to secure your API, read this guide on JWT Authentication in FastAPI.
- Deploying the full-stack application to a cloud server.
These improvements will help you build production ready full-stack applications using Next.js and FastAPI.