Next.js Build Error: ” Route.js couldn’t be rendered statically because it accessed request.url”

I’m working on a Next.js project and encountering an issue when trying to export the build. The error suggests that an API route is being prerendered, which results in a failure because it accesses request.url. Below are the details:

Problem :
When I run npm run build to create an optimized production build, I encounter an error that suggests Next.js is attempting to prerender my API route. This fails because the route accesses request.url, which is not available at build time. API routes should not be statically pre-rendered.

Error Message:

adee@Adees-MacBook-Air build % npm run build

Environments: .env.local, .env
Creating an optimized production build ...
✓ Compiled successfully
✓ Linting and checking validity of types
✓ Collecting page data
Generating static pages (0/9) [ ]
Error occurred prerendering page "/api/cards". Read more: https://nextjs.org/docs/messages/prerender-error

Error: Route /api/cards with `dynamic = "error"` couldn't be rendered statically because it accessed `request.url`.

at Object.get (/Users/adee/Web-Development/build/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:38816)
at c (/Users/adee/Web-Development/build/.next/server/app/api/cards/route.js:1:1318)
at /Users/adee/Web-Development/build/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:34672
at /Users/adee/Web-Development/build/node_modules/next/dist/server/lib/trace/tracer.js:140:36
at NoopContextManager.with (/Users/adee/Web-Development/build/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:7062)
at ContextAPI.with (/Users/adee/Web-Development/build/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:518)
at NoopTracer.startActiveSpan (/Users/adee/Web-Development/build/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18093)
at ProxyTracer.startActiveSpan (/Users/adee/Web-Development/build/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18854)
at /Users/adee/Web-Development/build/node_modules/next/dist/server/lib/trace/tracer.js:122:103
at NoopContextManager.with (/Users/adee/Web-Development/build/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:7062)
Generating static pages (8/9) [== ][

Directory Structure:

/public
  - assets...
/src
  /app
    /api
      /cards
        route.js

API Route Code (src/app/api/cards/route.js):

import { NextResponse } from "next/server";
import { query } from "../../../lib/db";

export const GET = async (req) => {
  const { searchParams } = new URL(req.url);
  const location = searchParams.get('location') || 'all';
  const month = searchParams.get('month') || 'default';
  const sort = searchParams.get('sort') || 'default';
  const searchKey = searchParams.get('search') || '';

  try {
    let queryStr = `SELECT * FROM card WHERE 1`;

    if (location !== 'all') {
      queryStr += ` AND departlocation = ?`;
    }

    if (month !== 'default') {
      queryStr += ` AND monthyear = ?`;
    }

    if (searchKey.trim() !== '') {
      queryStr += ` AND tourName LIKE ?`;
    }

    if (sort === 'lowToHigh') {
      queryStr += ` ORDER BY price ASC`;
    } else if (sort === 'highToLow') {
      queryStr += ` ORDER BY price DESC`;
    }

    const values = [];
    if (location !== 'all') {
      values.push(location);
    }

    if (month !== 'default') {
      values.push(month);
    }

    if (searchKey.trim() !== '') {
      const searchParam = `%${searchKey}%`;
      values.push(searchParam);
    }

    const results = await query({
      query: queryStr,
      values: values,
    });

    return NextResponse.json(results);
  } catch (e) {
    return NextResponse.json({ message: e.message }, { status: 500 });
  }
};

Fetch Code:

useEffect(() => {
  const fetchCards = async () => {
    setLoading(true);
    try {
      const response = await fetch(`/api/cards?location=${filterOption}&sort=${sortOption}&month=${month}&search=${searchKey}`);
      console.log(searchKey)
      if (!response.ok) {
        throw new Error('Failed to fetch cards');
      }
      const data = await response.json();
      setCards(data);
      setHasMore(data.length > 0);
    } catch (error) {
      console.error("Error fetching cards:", error);
      setCards([]);
      setHasMore(false);
    } finally {
      setLoading(false);
    }
  };

  fetchCards();
}, [filterOption, sortOption, month,searchKey]);

Any help or insights would be greatly appreciated!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật