OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

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

  • Thread starter Thread starter Adee Shaikh
  • Start date Start date
A

Adee Shaikh

Guest
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 pre-rendered, 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 pre-render 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:

Code:
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:

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

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

Code:
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:

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!

<p>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 pre-rendered, which results in a failure because it accesses request.url. Below are the details:</p>
<p>Problem :<br />
When I run <code>npm run build</code> to create an optimized production build, I encounter an error that suggests Next.js is attempting to pre-render 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.</p>
<p>Error Message:</p>
<pre class="lang-none prettyprint-override"><code>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) [== ][
</code></pre>
<p>Directory Structure:</p>
<pre><code>/public
- assets...
/src
/app
/api
/cards
route.js

</code></pre>
<p>API Route Code (src/app/api/cards/route.js):</p>
<pre><code>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 });
}
};

</code></pre>
<p>Fetch Code:</p>
<pre><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]);

</code></pre>
<p>Any help or insights would be greatly appreciated!</p>
 
Top