Cache on route.ts

I have two routes, one route catch all metrics

export async function GET(req: NextRequest) {
  return paginate(req, async (page: number, limit: number) => {
    try {
      const offset = (page - 1) * limit;

      const countResult = await pg('readings_temperature').count('* as count').first();

      const count = Number(countResult?.count || 0);

      const data = await pg('readings_temperature').select('*').limit(limit).offset(offset);

      const totalPages = Math.ceil(count / limit);

      const pagination = {
        page,
        per_page: limit,
        first_page: 1,
        last_page: totalPages,
        total_pages: totalPages,
        total_records: count,
      };

      return NextResponse.json(
        {
          status: 200,
          message: 'Successfully received data.',
          pagination,
          data,
        },
        { status: 200 }
      );
    } catch (err) {
      console.error('Error occurred:', err);
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      return NextResponse.json({ status: 500, message: 'Failed to load data', error: errorMessage }, { status: 500 });
    }
  });
}

And other route catch the newest metric

import { NextResponse } from 'next/server';
import pg from '../../connection';

export async function GET() {
  try {
    const latestData = await pg('readings_temperature').select('*').orderBy('created_at', 'desc').first();

    if (!latestData) {
      return NextResponse.json({ status: 404, message: 'No data found.' }, { status: 404 });
    }

    return NextResponse.json(
      {
        status: 200,
        message: 'Successfully received the latest data.',
        data: latestData,
      },
      { status: 200 }
    );
  } catch (err) {
    console.error('Error occurred:', err);
    const errorMessage = err instanceof Error ? err.message : 'Unknown error';
    return NextResponse.json({ status: 500, message: 'Failed to load data', error: errorMessage }, { status: 500 });
  }
}

The first route (catch all) they don’t creating cache but the other route don’t work in other times, only work after deploy, in localhost works correctly but on vercel deploy is cache data, other route don’t cache in vercel

Header example for last route i show yours

accept-ranges: bytes
access-control-allow-origin: *
age: 878
cache-control: public, max-age=0, must-revalidate
content-disposition: inline
content-type: application/json
date: Thu, 12 Sep 2024 01:32:11 GMT
etag: "d349be152dc0ba3e1bbb3c8cfb269785"
server: Vercel
strict-transport-security: max-age=63072000; includeSubDomains; preload
vary: RSC, Next-Router-State-Tree, Next-Router-Prefetch
x-matched-path: /api/temperature/getLatest
x-vercel-cache: HIT
x-vercel-id: gru1::dzjm8-1726104731726-35fa96cbc7f4
content-length: 166

I tested on edge, chrome and insominia

They in same project but separated folders

I resolved using on initial lines

export const dynamic = 'force-dynamic';

and his works fine

Complete code:

import { NextResponse } from 'next/server';
import pg from '../../connection';

export const dynamic = 'force-dynamic';

export async function GET() {
  try {
    const latestData = await pg('readings_temperature').select('*').orderBy('created_at', 'desc').first();

    if (!latestData) {
      return NextResponse.json(
        { status: 404, message: 'No data found.' },
        {
          status: 404,
        }
      );
    }

    return NextResponse.json(
      {
        status: 200,
        message: 'Successfully received the latest data.',
        data: latestData,
      },
      {
        status: 200,
      }
    );
  } catch (err) {
    console.error('Error occurred:', err);
    const errorMessage = err instanceof Error ? err.message : 'Unknown error';
    return NextResponse.json(
      { status: 500, message: 'Failed to load data', error: errorMessage },
      {
        status: 500,
      }
    );
  }
}
1 Like

Thanks for sharing this, @luwroblewski!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.