Next Dot JS API Kaching using Redis and Seola

by SkillAiNest

When you hear about the next dot J, your first thinking may be a static website or a reacting front. But this is just one part of the story. Next. JS can also strengthen the full -fledged APIS with full features that can host and host you like any other passenger service.

In an earlier article, I went by building the next dot JS API and deploying it with Seola. For example, the data was stored in the postgrass QL Database and handled the requests directly. It did well, but as traffic increases, the database targeting at every request may slow down.

It comes from here. By adding the Redis as a cache layer, we are next. JS API can make it very fast and more efficient. In this article, we will see how to add Redis Catching to your API, deploy it with CivicAnd show improvement in measurements.

In the last article, I explained the API in detail. So you can Use this reservoir To start as the project base.

The table of content

Why are catching cases

Whenever your API database is hit, it costs time and resources. Databases are great to store and inquire into structural data, but when you need to submit thousands of reading requests every second, they do not improve the speed of a scale.

Catching solves it by keeping the frequently access data in memory. Each time, instead of asking the database, API is available if it is available can return the data directly from the cache. Redis its Perfect is excellent because it is a key price store in a memory designed for performance.

For example, if you bring users from the database on each request, it may take 200 mm to run the inquiry and return results. With redis catching, the first application saves the result in the memory, and then the applications can return the same data to less than 10 mm. This is an order of Magnite improvement.

What is Redis?

Redis is a data store in a memory that acts like a super -fast database. Instead of writing and reading from the disk, it keeps the data in memory, which makes it incredibly faster. This is why it is often used as a cache, where speed is more important than long -term storage.

It is designed to handle high thropped work loads with little delay, which means it can respond in micro -seconds. This makes it a great fit to strengthen real -time applications such as Catching API reactions, session data, or chat systems and leader boards.

Unlike the traditional database, Redis is focused on simplicity and speed. It stores data as a key value pair, so you can bring or update values ​​without writing complex questions. And since it supports high data types such as lists, sets and hashtas, it is far more flexible than a simple key price store.

When we have built with an API in the next dot J, Redis helps you reduce the burden on the main database and provide customers with a blizzing fast response.

The establishment of the project

Let’s Store Clone:

git clone git@github.com:manishmshiva/nextjs-api-pgsql.git next-api

Now let’s go to the directory and install the NPM to install the packages.

cd next-api
npm i

Create an .env file and add the database URL from Seola to the environmental variable.

cat .env

the .env file should look like:

PGSQL_URL=postgres:

Now let’s make sure that the application works as expected by starting application and making a couple of API applications.

Starting app:

npm run dev

Let’s make sure the database is connected. Barley localhost:3000 On your browser it should return the following JSON:

Get /

Let’s create a new user. Using a new entry in DB PostmanSend a post request with the following JSON:

{"id":"d9553bb7-2c72-4d92-876b-9c3b40a8c62c","name":"Larry","email":"larry@example.com","age":"25"}

Postman test

Let’s make sure that the record is born localhost:3000/users In the browser

/Postman's response for users

Great Now use these APIs using Redis.

Supply Redis

Let Of cesola Click the dashboard and the “database”. Select “Redis” from the list, and leave the rest of the option as default.

Create a database

Once the database becomes, change the “external connection” option and copy the publicly accessible URL.

Update network settings

Should see in the .env file:

REDIS_URL=redis:

Now install the Redis Client for Node Dot J:

npm install ioredis

We can now contact Redis and use it as a cache layer for its users API. Let’s see how to enforce the catching.

Updating cache on reading

Here’s a refreshing users/route.ts Which reuses:

import { NextResponse } from "next/server";
import { Client } from "pg";
import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL!);

async function readUsers() {
  const client = new Client({
    connectionString: process.env.PGSQL_URL,
  });
  await client.connect();

  try {
    const result = await client.query("SELECT id, name, email, age FROM users");
    return result.rows;
  } finally {
    await client.end();
  }
}

export async function GET() {
  try {
    
    const cached = await redis.get("users");
    if (cached) {
      return NextResponse.json(JSON.parse(cached));
    }

    
    const users = await readUsers();

    
    await redis.set("users", JSON.stringify(users), "EX", 60);

    return NextResponse.json(users);
  } catch (err) {
    return NextResponse.json({ error: "Failed to fetch users" }, { status: 500 });
  }
}

Now, when you will kill /users:

  1. API checks again.

  2. If the data is available, he returns it immediately.

  3. If not, it inquires from the postgrade QL, as a result saves Redis, and then returns it.

This repeatedly accelerates applications. You can adjust to the expiration of cache (EX 60) Depending on how your data needs to be refreshed.

Without a catching, recovered /users Ten times means ten database questions. Each database depends on the size and the delay in the network.

With Redis, the first application still takes ~ 200 mm as it settled the cache. But every subsequent application is almost less than 10Ms, almost immediately. It’s a 20x improvement.

This speedup is important when your API faces hundreds or thousands of requests. Catching not only reduces the delay but also lightens the burden on your database.

Updating cache on writing

Now, just use the application cache. But what if we add new users? The cache will still return the old data.

The solution is that whenever there is a writing, the cache is to be updated or cleaned. Let’s update POST Handler:

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const client = new Client({
      connectionString: process.env.PGSQL_URL,
    });
    await client.connect();

    const query = `
      INSERT INTO users (id, name, email, age)
      VALUES ($1, $2, $3, $4)
      RETURNING *;
    `;

    const result = await client.query(query, (
      body.id,
      body.name,
      body.email,
      body.age,
    ));

    await client.end();

    
    await redis.del("users");

    return NextResponse.json(result.rows(0));
  } catch (err) {
    return NextResponse.json({ error: "Failed to add user" }, { status: 500 });
  }
}

Now whenever a new user is formed, cache for users Clean. The next gate application will be brought from the database, refreshes the cache, and then continues to serve the ketchode data.

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.

Seola creation 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.

Create a new app

Click “Create” and “Create and Deploy”. We have not included our postgrass QLURL and Redis URL as environmental variables, 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. Do the same for the “Reds_ver” key and add the Redis URL.

Adding environmental variables

Now go back to the “Review” section and click “now”.

App deployed

Once deployed. After completion, click “View the app” to get your API’s URL directly. You can change Local Host: 3000 Test your API with a new URL in the postman.

Why Redis does good work with next dot JS APIS

Redis is lightweight, running fast, and API reaction is perfect for catching. In the context of the next dot J, it naturally fits because:

  • APIs run the server side where direct inquiries can be made directly.

  • Catching logic is easy to add around database calls.

  • Redis can be used for more than catching – limiting rates, session storage, and all things like pub/all are common samples.

By adding the Reds to the Next Dot JS, Postgrass QL, and Seola, you find a stack that is fast, expanding and easy to deploy.

Conclusion

Catching is not just a correction-this is a real world APIS. Next Dot JS helps you create strong bakend APIS, which can be easily deployed. By adding reds to the mix, they can handle the scale without breaking the APIS sweat.

Seola connects it all together by hosting a systematic postgrass QL, Redis, and app in one place. With some of the environment variables and a gut hub repo, you can go to the local giant for a production, to reach the ketchard API in minutes.

Hope you enjoy this article. Sign up for my free AI newsletter turningtalks.ai For more lessons on AI. You can find me too Linked.

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro