Next.js Discord

Discord Forum

Getting error in api routes after enabling cacheComponents

Unanswered
Oak shoot sawfly posted this in #help-forum
Open in Discord
Oak shoot sawflyOP
I am getting various error. I just enabled and tried to build the application.
Error while searching snippet Error: Route /api/snippets/semantic needs to bail out of prerendering at this point because it used nextUrl.searchParams.
    at lY (turbopack:///[project]/src/app/api/snippets/semantic/route.ts:10:31)
   8 |
   9 |
> 10 |     const q = request.nextUrl.searchParams.get("q");
     |                               ^
  11 |
  12 |
  13 |     const vector = await generateEmbedding(q!); {
  digest: 'NEXT_PRERENDER_INTERRUPTED'
}


Like these I am getting error in other files too

6 Replies

Oak shoot sawflyOP
Error in logout route Error: During prerendering, `cookies()` rejects when the prerender is complete. Typically these errors are handled by React but if you move `cookies()` to a different context by using `setTimeout`, `after`, or similar functions you may observe this error and you should handle it in that context. This occurred at route "/api/auth/logout".
    at new Promise (<anonymous>)
    at l (turbopack:///[project]/src/app/api/auth/logout/route.ts:8:31)
   6 | export const GET = async (req: Request) => {
   7 |   try {
>  8 |     const cookieStore = await cookies();
     |                               ^
   9 |
  10 |     const authCookie = cookieStore.get(AUTH_CONSTANTS.SESSION_COOKIE);
  11 |     if (!authCookie) { {
  route: '/api/auth/logout',
  expression: '`cookies()`',
  digest: 'HANGING_PROMISE_REJECTION'
}
@alfonsüs ardani send code for src/app/api/snippets/semantic/route.ts
Oak shoot sawflyOP
import { generateEmbedding } from "@/lib/embedding";
import { qdrantClient } from "@/lib/qdrant";
import { NextRequest } from "next/server";


export async function GET(request: NextRequest) {
  try {
    
    const q = request.nextUrl.searchParams.get("q");

    const now = performance.now();
    const vector = await generateEmbedding(q!);

    const collections = await qdrantClient.getCollections();
    console.log(
      "Available collections:",
      collections,
      collections.collections.map((c) => c.name)
    );

    const collectionInfo = await qdrantClient.getCollection(
      process.env.QDRANT_COLLECTION!
    );
    console.log("Collection info:", collectionInfo);

    const results = await qdrantClient.search(process.env.QDRANT_COLLECTION!, {
      vector,
      limit: 5,
      with_payload: true,
    });

    const processingTime = performance.now() - now;
    if (results.length === 0)
      return Response.json({
        hits: [],
        totalHits: results.length,
        processingTime,
        query: q!,
      });

    const modifiedResults = results
      .filter((r) => r.score > 0.3)
      .map((r) => ({
        id: r.payload?.id ?? "",
        title: r.payload?.title ?? "",
        language: r.payload?.language ?? "",
        score: r.score,
      }));

    return Response.json({
      hits: modifiedResults,
      totalHits: modifiedResults.length,
      processingTime,
      query: q!,
      rawResults: results,
    });
  } catch (error) {
    console.log("Error while semantic searching snippet", error);
    return Response.json(
      {
        error: {
          code: "SERVER_ERROR",
          message: "Something went wrong",
        },
      },
      { status: 500 }
    );
  }
}
@alfonsüs ardani you have to re-throw or re-position `await cookies()`
Oak shoot sawflyOP
Sorry I didn't get it. What changes do I need to make??
logout.ts
import { AUTH_CONSTANTS } from "@/features/auth/constant";
import { logoutUser } from "@/features/auth/services";
import { aesDecrypt, EncryptionPurpose } from "@/features/auth/utils/aes";
import { cookies } from "next/headers";

export const GET = async (req: Request) => {
  try {
    const cookieStore = await cookies();

    const authCookie = cookieStore.get(AUTH_CONSTANTS.SESSION_COOKIE);
    if (!authCookie) {
      return Response.json(
        {
          error: {
            code: "UNAUTHORIZED",
            message: "Unauthorized",
          },
        },
        { status: 401 }
      );
    }

    const decryptedSessionId = aesDecrypt(
      authCookie.value,
      EncryptionPurpose.SESSION_COOKIE_SECRET
    );

    await logoutUser(Number(decryptedSessionId));
    cookieStore.delete(AUTH_CONSTANTS.SESSION_COOKIE);

    return Response.json(
      {
        success: true,
      },
      { status: 200 }
    );
  } catch (error) {
    console.log("Error in logout route", error);
    return Response.json(
      {
        error: {
          code: "SERVER_ERROR",
          message: "Something went wrong",
        },
      },
      { status: 500 }
    );
  }
};