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!