Next.js + FastAPI Tutorial: Connect Frontend to Backend Step-by-Step | Web Engineering Notes
Next.js + FastAPI Tutorial: Connect Frontend to Backend Step-by-Step
Mar 11, 2026
Next.jsFastAPIFull-Stack
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 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.
FastAPI + SQLAlchemy Tutorial: Build a CRUD API Step-by-Step for Beginners
This tutorial teaches beginners how to build a CRUD API with FastAPI and SQLAlchemy. You’ll learn project setup, database connection, models, Pydantic schemas, CRUD functions, API routes, and testing using Swagger UI. By the end, you will have a fully functional backend API ready to use.
How to Fix Website Changes Not Showing in Next.js | A Step By Step Solution
Website changes not showing even after restart can be frustrating.
This guide explains the real causes behind this issue in Next.js production, including build problems, browser caching, and PM2 process errors, with clear step-by-step fixes.
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:
bash
Next.js (Frontend) ↓Fetch API Request ↓FastAPI (Backend) ↓JSON Response ↓Display Data in the UI
Step-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.
bash
mkdir fastapi-backendcd fastapi-backend
This 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:
bash
python -m venv venv
Activate the virtual environment:
Mac/Linux:
bash
source venv/bin/activate
Windows:
bash
venv\Scripts\activate
After activation you should see (venv) in your terminal.
Step 3 – Install Required Packages
Now install the required backend packages.
bash
pip install fastapi uvicorn
These 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
bash
touch main.py
Now open the file and add the following code:
python
from fastapi import FastAPIapp = 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.
bash
uvicorn main:app --reload
Explanation of the command:
main – the python file name
app – the FastAPI instance
--reload – automatically reload the server when code changes
Step 6 – Test the Backend
Open the browser and visit:
bash
http://127.0.0.1:8000
You should see the following responses:
json
{ "message": "FastAPI backend is running"}
FastAPI also automatically generates interactive API documentation.
Open:
bash
http://127.0.0.1:8000/docs
This 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 automatically generates API documentation using Swagger UI.
Open:
bash
http://127.0.0.1:8000/docs
Find 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.
bash
npx create-next-app@latest nextjs-frontend
Follow the setup prompt. You can choose the default options or configure the project according to your own preferences.
Then navigate to the project folder.
bash
cd nextjs-frontend
Step 2 – Start the Development Server
Run the following command to start the development server:
bash
npm run dev
Once the server start, open your browser and visit:
bash
http://localhost:3000
You 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:
package.json — contains project dependencies and scripts
Step 4 – Editing the Main Page
Open the file:
bash
app/page.js
Replace the existing code with a simple placeholder UI.
js
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:
bash
http://127.0.0.1:8000/users
When called, it returns a JSON response like this:
After adding the middleware, restart the FastAPI server:
bash
python main:app –reload
Now the backend allows incoming requests from the Next.js frontend.
Step 4 – Test the Connection Again
Make sure both servers are running.
FastAPI
bash
uvicorn main:app --reload
Next.js
bash
npm run dev
Open the frontend again:
bash
http://localhost:3000
The 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.
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:
bash
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:
python
from fastapi.middleware.cors import CORSMiddlewareapp.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:
js
TypeError: Failed to fetch
Possible Causes:
The FastAPI server is not running
The API URL is incorrect
The port number is wrong
Solution:
Make sure the FastAPI is running:
bash
uvicorn main:app –reload
Then verify the API works by opening the URL in your browser:
bash
http://127.0.0.1:8000/users
If 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.
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:
js
"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:
bash
Next.js (Frontend) ↓API Request (fetch) ↓FastAPI (Backend) ↓JSON Response ↓Data Rendered in the UI
Understanding 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.