When developers think of the next dot J, they often associate it with SEO -friendly static websites or reacting Frontands. But many remember how the next dot J can be used to build a full-fledged APIS-all of them are within the same project.
I have recently written an article on working with Next Dot JS API and deploying it in production. In this case, I use the JSON file as a mini database.
But JSON or any type of file storage production application is not fit. The reason is that file -based storage is not designed to access harmony, so many data writing users can cause corruption or damage at the same time.
It also lacks indexing and inquiry capabilities, which increases the data. It is also difficult to manage backup, security, and scales than the appropriate database.
Recently. , While JSON files work for a demo or prototype, the production system requires a database that can handle harmony, major datases, complex questions and reliable perseverance.
So in this article, we will follow the REST API method with the next dot J, store data in a Seola -administered database, and deploy the entire project into production using Seola’s PAAS infrastructure.
The table of content
What’s the next?
Next Dot Jay There is an open source rectal framework developed by Versel. This server is known for side rendering, static breed and smooth routing. But beyond the superpower in front of it, it allows developers to create baked logic and APIS through a file -based routing system. Next.com is a great choice for the construction of full stack apps.
Installed and setup
To start, make sure the node Dot JS and NPM are installed.
$ node --version
v22.16.0
$ npm --version
10.9.2
Now, a new next. Create JS Project:
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 Next JS API
Now that we have set our API template, let’s write a basic REST API which has two points: to make a data and to see a data
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.
Here is a setup screenshot. Delete the (slug) directory with the project as it will not be relevant to us.
CRARAD OPERS FOR ROTTTTS FIL / (This is the place where “Hello World” was born)
Route Dot TS File handle crude operations for users /users
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 two routes:
We will use a database to store our records. We are not going to install a database on our local machine. Instead, we will supply the database in the cloud and use it with our API. This approach is common in a test / production environment to ensure the consistency of the data.
Database supplies to 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 -free level, so we will use it to connect it to the database as well as to deploy our app in the cloud.
If you are new to Seola, you can Sign up Use your Gut Hub Account to enable direct deployment from your gut hub. Whenever you push the code to your project, Seola will deploy your app to the auto bridge and cloud.
Once you log in to Seola, click on the “database”.
Now let’s create a postgrade QL database.
Use default settings. Once the database becomes, it will disable external contacts through default for security to ensure that no one outside our server can connect. Since we want to test our contact with our local machine, let’s enable an external connection.
Under the external connection, we need to connect the database from our local closing point. Create a file called .env in the project and paste the URL in the bottom format:
PGSQL_URL=postgres:
The reason we use .env is to save the environment variable. In production, we will not need this file (never push the .env files into a bid). When we deploy the app, Seola will give us the option to incorporate environmental variables through GUI.
Now check our database connection. Install pg
Package to communicate with Postgres QL for the node. Let’s also install the extension of the type script pg
Supporting type script definitions.
$ npm i pg
$ npm install --save-dev @types/pg
Change Route Dot TS that presented “Hello World” in the bottom:
import { NextResponse } from "next/server";
import { Client } from "pg";
export async function GET() {
const client = new Client({
connectionString: process.env.PGSQL_URL,
});
try {
await client.connect();
await client.end();
return NextResponse.json({ message: "Connected to database" });
} catch (error) {
console.error("Database connection error:", error);
return NextResponse.json({ message: "Connection failed" }, { status: 500 });
}
}
Now that your app and the local host: go to 3000, it should be called “linked to the database”.
Great Now let’s write our two routes, one to make the data and the other to see the data we have developed. Use this code under users/route dot ts:
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { Client } from "pg";
interface User {
id: string;
name: string;
email: string;
age: number;
}
function getClient() {
return new Client({
connectionString: process.env.PGSQL_URL,
});
}
async function readUsers(): Promise<User()> {
const client = getClient();
await client.connect();
try {
const result = await client.query("SELECT id, name, email, age FROM users");
return result.rows;
} finally {
await client.end();
}
}
async function writeUsers(users: User()) {
const client = getClient();
await client.connect();
try {
const insertQuery = `
INSERT INTO users (id, name, email, age)
VALUES ($1, $2, $3, $4)
ON CONFLICT (id) DO UPDATE SET
name = EXCLUDED.name,
email = EXCLUDED.email,
age = EXCLUDED.age;
`;
for (const user of users) {
await client.query(insertQuery, (user.id, user.name, user.email, user.age));
}
} finally {
await client.end();
}
}
export async function GET() {
try {
const users = await readUsers();
return NextResponse.json(users);
} catch (err) {
console.error("Error reading users from DB:", err);
return NextResponse.json({ error: "Failed to fetch users" }, { status: 500 });
}
}
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const users: User() = Array.isArray(body) ? body : (body);
await writeUsers(users);
return NextResponse.json({ success: true, count: users.length });
} catch (err) {
console.error("Error writing users to DB:", err);
return NextResponse.json({ error: "Failed to write users" }, { status: 500 });
}
}
Now when you go to the Local Host: 3000/users, it will give you a mistake because there is a consumer table. So let’s make one.
In the database UI, click “Studio”. You will find a visual editor for your database where you can manage your data directly (very cool, fine?).
Press “+” icon and select “Create Table”. Create a table with schemes below. Click the “Add Column” link to create a new column.
“Click the table and you should see the designed table like below:
Let’s add a dummy record using the “Record” button to use our API. The ID field should be in the Uuid format (and you can Create one here,
Now check our API.
You should see the user designed as a local host response: 3000/users’ inquiry. Now create a new user using our API.
We will use Postman It is easy to make post applications using Post Postman. We will send sample data under “Body” → “RAW” → “JSON”.
The answer by the postman should be below:
Now Local Host: Going to 3000/Customers, you should create a new record.
Great work! Now let’s get this app directly.
Deployed in the seola.
Press your code on Gut Hub or Fork my repository. Now allows to go to Seola and create a new app.
Choose your reservoir from the dropdown and check “automatically deployment to the commit”. This will ensure that the deployment is automatic whenever you move the code forward. Choose “hobbies” under the resource section.
Click “Create” and “Create and Deploy”. We have not included our postgrade QLURL as an environmental variable, so if you try to deploy it, the app will crash.
Go to the “Environmental variables” section and add the key “PGSQL_URL” and URL in the value field.
Now go back to the “Review” section and click “now”.
Once deployed. After completion, click “View the app” to get your API’s URL directly. You can change the Local Host: 3000 with a new URL in the postman and test your API.
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
Conclusion
Next Dot J is no longer just a front and framework. It is a powerful full stack platform that allows you to produce and deploy APIS ready for production with minimal friction. By connecting it to Seola’s developer friendly infrastructure, you can go directly from local development in minutes to cloud host API.
In this tutorial, you learned how to set up the next dot JS API project, connect it to Seola’s Cloud Hosted Postgrass QL Database, and deploy everything without interruption. Whether you are making a small side project or the entire scale application, this stack provides you with speed, structure and scalebuability of rapid moving without losing flexibility.
Hope you enjoy this article. I’ll see you soon. You can Contact me here Or Go to my blog.