When people hear about Next Dot J, they often think about server side rendering, reacting frontands, or SEO-optimized static websites. But in this powerful framework there is more than just front and development.
Next Dot JS developers also allow for a direct, expanding back and APIS within the same code base. It is particularly valuable for small to medium applications, where firmly firmly integrated by the front end and backward growth and deployment.
In this article, you will learn that the next dot J will make the API making and deploy it to production using Seola. It is relatively easy to learn how to build something using tutorials – but the real challenge is to bring it into the hands of consumers. Doing so turns your project into a real and usable thing from a local prototype.
The table of content
What’s the next?
Next Dot Jay An open source is a react framework made by Versal. This enables developers to build a server -offered and stable web applications.
It mainly summarizes the setting and boiler plate needed to run the full stack react application, which makes it easier for developers to focus on construction features rather than the formation of infrastructure.
Although it began as a solution to Frontand challenges in response, it is developed in a complete stack framework that allows you to handle the backbone logic, interact with the database and build APIS. This united code base is what next. Forcing JS especially modern web development.
Installed and setup
Let’s install next. JS Make sure you have node.js And NPM has been installed on your system, and that they are the latest version.
$ node --version
v22.16.0
$ npm --version
10.9.2
Now let’s create the next dot JS project. The order to do this is:
$ npx create-next-app@latest
The result of the above command will ask you a lot of questions to configure your app:
What is your project named? my-app
Would you like to use TypeScript? No / Yes
Would you like to use ESLint? No / Yes
Would you like to use Tailwind CSS? No / Yes
Would you like your code inside a `src/` directory? No / Yes
Would you like to use App Router? (recommended) No / Yes
Would you like to use Turbopack for `next dev`? No / Yes
Would you like to customize the import alias (`@/*` by default)? No / Yes
What import alias would you like configured? @/*
But this tutorial L, We are not interested in a complete stack app – just one API. So let’s re -create the app using it — - api
Flag
$ npx create-next-app@latest --api
It will still ask you some questions. Use default settings and finish the app.
Once setup, you can see the folder with your app name. Let’s go to the folder and run the app.
$ npm run dev
Your API template is running at 3000. Go And you should see the following message:
{
"message": "Hello world!"
}
How to build REST API
Now that we have set our API template, let’s write a basic Rest API. A basic Rest API is just four closing points: Create, Read, Refuse, Delete (also known as CRUD).
Generally, we will use a database, but for simplicity, we will use the JSON file in our API. Our goal is to create a Rest API that can read and write this JSON file.
The API code will remain under the project directory /under the app. Next dot uses file -based routing to build JSURL routes.
For example, if you want a URL route /users, you should have a directory called “Users” with a Route Dot TS file to handle all CRUD operations for users. /Customers /: For ID, you should have a directory called “ID) under the” ID) which has a Route Dot TS file. Square brackets are to tell the next dot J that you expect dynamic values for /consumers /: ID route.
Reading and writing data to your paths You should also have users within your /app /users’ directory.
Here is a setup screenshot. Delete the coming (slug) directory with the project because it will not be relevant to us:
Route Dot TS Handle Crowd Operations for File / In File
Route Dot TS File handle crude operations for users /users
Route Dot TS File/Customers/(ID)/Handle Crude Operations Under/Customers/: ID where ‘ID’ will be dynamic value.
Under users /users will be our data store.
Although this setup may be complicated for a simple project, it provides a clear structure for large -scale web applications. If you want to go deeper in construction of complex APIS with the next dot J, This is a lesson You can follow.
Under the code is the default file for our API API. You get it a request for the request and “Hello World!” Can see while responding with:
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({ message: "Hello world!" });
}
Now we need five routes:
Get /Euppy → Create all users list
Get /users /: ID → Create a User List
Post /Users A Create a New User
PUT /users /: ID → Update current user
Delete /Users /: Id Relive Delete Current User
Root Dot TS file code under /app /users:
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { promises as fs } from "fs";
import path from "path";
interface User {
id: string;
name: string;
email: string;
age: number;
}
const usersFile = path.join(process.cwd(), "app/users/users.json");
async function readUsers(): Promise<User()> {
try {
const data = await fs.readFile(usersFile, "utf-8");
return JSON.parse(data) as User();
} catch {
return ();
}
}
async function writeUsers(users: User()) {
await fs.writeFile(usersFile, JSON.stringify(users, null, 2), "utf-8");
}
export async function GET() {
const users = await readUsers();
return NextResponse.json(users);
}
export async function POST(request: NextRequest) {
const body = await request.json();
const { name, email, age } = body as {
name?: string;
email?: string;
age?: number;
};
if (!name || !email || age === undefined) {
return NextResponse.json(
{ error: "Missing name, email, or age" },
{ status: 400 }
);
}
const users = await readUsers();
const newUser: User = {
id: Date.now().toString(),
name,
email,
age,
};
users.push(newUser);
await writeUsers(users);
return NextResponse.json(newUser, { status: 201 });
}
Now/app/users/(ID) /route.ts file code:
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { promises as fs } from "fs";
import path from "path";
interface User {
id: string;
name: string;
email: string;
age: number;
}
const usersFile = path.join(process.cwd(), "app/users/users.json");
async function readUsers(): Promise<User()> {
try {
const data = await fs.readFile(usersFile, "utf-8");
return JSON.parse(data) as User();
} catch {
return ();
}
}
async function writeUsers(users: User()) {
await fs.writeFile(usersFile, JSON.stringify(users, null, 2), "utf-8");
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const id = (await params).id;
const users = await readUsers();
const user = users.find((u) => u.id === id);
if (!user) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
return NextResponse.json(user);
}
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const id = (await params).id;
const body = await request.json();
const { name, email, age } = body as {
name?: string;
email?: string;
age?: number;
};
const users = await readUsers();
const index = users.findIndex((u) => u.id === id);
if (index === -1) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
users(index) = {
...users(index),
...(name !== undefined ? { name } : {}),
...(email !== undefined ? { email } : {}),
...(age !== undefined ? { age } : {}),
};
await writeUsers(users);
return NextResponse.json(users(index));
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
const id = (await params).id;
const users = await readUsers();
const index = users.findIndex((u) => u.id === id);
if (index === -1) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
const (deleted) = users.splice(index, 1);
await writeUsers(users);
return NextResponse.json(deleted);
}
We will have an empty row inside the Votapp/users.json. You can find all the code here In this reservoir.
How to test API
Let’s now examine the closing points of the API.
First, let API run:
$ npm run dev
You can go /Users And can see an empty row because we have not advanced any user’s information.
From the code, we can see that a user requires a nam, email and age because the ID is automatically developed in the post closing point.
We will use Postman Applying applications to API and making sure API behaves as expected.
- Get /Customers: This will be empty on our first effort because we have not yet given any data.
- Post /Users: Create a new user. Under the “body”, choose “raw” and select “JSON”. This is the data we are sending API. Json will be body
{"name":"Manish","age":30, "email":"manish@example.com"}
I will make another record called “Larry”. Here is JSON:
{"name":"Larry","age":25, "email":"larrry@example.com"}
Now let’s see users. You want /users want to see two entries of our application.
Now let us /users /: see the same user using the ID.
Now let’s update Larry’s age to 35. We /Customers /: The PUT application to the ID will only pass in the body of the application.
Now delete Larry’s record.
If you check users you should just see a record:
So we have constructed and examined our API. Let’s get it directly.
How to deploy in Seola
Civic Is a modern, use -based platform service provider and is an alternative to sites like Heroco or your self -made setup on AWS. It connects powerful features with a smooth manufacturer’s experience.
Seouls offer your plans hosting application hosting, database, object storage, and static site. It comes with a generous level, so let’s see how to deploy our API into the cloud using Seola.
Make sure you have a code with gut hub or Fork my repository For this project. If you are new to Seola, you can sign up using your Gut Hub account to enable direct deployment from your Gut Hub account. Whenever you push the code to your project, Seola will deploy your app to the auto bridge and cloud.
Once you Log Click Seola, “Applications”. Now create an app.
If you have verified with the Gut Hub, the application creation will show a list of interface reserves. If you have fork it from my reservoir that you have pushed your code or choose the Next JSPI project.
Check the box “Auto Deployment” box. This will ensure that your latest code auto has been posted in Seola. Now, let’s choose an example in which we can deploy the application. Each server comes with its prices based on capacity.
Let’s choose a hobby server cost $ 5/mo. Seola gives us $ 50 free levels, so we don’t have to pay anything unless we exceed this use level.
Now, click “Create and Deploy”. This should draw our code from our reservoir, run the blood process, set a dock container and then deploy the app. Usually the work of Sysdamine, is fully automated by Seola.
Wait a few minutes to all the above. You can see the log in the “deployment” interface.
Now, click on the “View app” and you will find your API directly with the URL (ending with the Seola.com). You can convert “” “with a new URL and run the same test using a postman.
Congratulations – now your app is straight. You can work more with your app using Admin Interface, such as:
Monitor your app’s performance
View Real Time Logs
Add customs domains
Update network settings (open/closed ports for security, and so on)
Add more storage
The Seola also provides the resources of the Object Storage, the Database, Cash, and similar resources, which are beyond the scope of this tutorial. But it allows you to monitor, manage and scale your application without the need for a system administrator. This is the beauty of the PAAS system. Here is a detailed comparison of VPS vs PAAS system to host the application.
Conclusion
In this article, we went beyond the next dot Ji’s general front and use case and searched its abilities as a complete stack framework. We created a complete Rest API using the app rotor and file -based routing, which contains the data contained in the JSON file. After that, we took it a step further and deployed API into production using Seola, a modern PAAs that automated deployment, scaling and surveillance.
This setup shows how developers can create and ship full stack applications such as Front End, Backland, and Deployment, all in the same next dot JS project. Whether you are typing or building for a scale, this workflow determines you with everything you need to get your apps quickly and efficiently in the hands of users.
Hope you enjoy this article. I’ll see you soon with someone else. Linked to contact me on them Or Visit my website.