Next.js Discord

Discord Forum

Failed to parse URL from /api/...

Unanswered
evandabest posted this in #help-forum
Open in Discord
This is my first time making an api in nextJS. I have all the code that is supposed to execute when I run the api but i keep getting a variation of cant find url.

the application flow goes like this...
User uploads pdf. It gets uploaded to supabase. the link is returned.
The user id (auth id), the link and the document id that is generated is passed to the server side where it is then inserted into the user's array of documents. This is the important part, the link of the pdf and the document id is used in the body of the api request. But when I try to use the api, I keep getting errors. I don't if it is bc of the way I set up the request or something else. This is the code and plz help me out.

client-side page
const add = async (e:any) => {
  //rest of the code...
  const post = async (e: any) => {

        e.preventDefault()

        if (!pdf) {
            console.error('No file selected');
            return;
        }

        if (!id) {
            console.error('No user id');
            return;
        }
        
        const time = Date.now()


        const {data, error} = await supabase.storage.from('pdfs').upload(`${id}_${time}`, pdf)

        if (error) {
            console.error('Error uploading pdfs:', error);
            return;
        }

        const publicUrl = await getURL(`${id}_${time}`);
        if (!publicUrl) {
            console.error('Error fetching public url');
            return;
        }

        router.push('/')
        
        await addPDF({id: id, url: publicUrl, documents: documents})
        
        
    }



    return (
        <>
            <input className="m-auto text-white border-2 border-white w-[80%] rounded-md" type="file" onChange={newFile} name="file" />
            <button className="m-auto text-white border-2 border-white w-[80%] rounded-md" onClick={post}>Submit</button>
        </>
    )

}

export default Add


server side actions file (actions.ts)
'use server'
import { createClient } from "@/utils/supabase/server"

export const addPDF = async ({id, url, documents }: {id: string, url: string, documents: string[]}) => {

    const supabase = createClient()

    const { data: updatedData, error: updateError } = await supabase.from('pdf').insert({
        link: url, 
    }).select("id").single()
    
    if (updateError) {
        console.error('Error uploading pdf:', updateError);
        return;
    }
    
    async function callChatAPI(urls: string, docID: string) {
        console.log(urls);
        console.log(docID);
        try {
            const response = await fetch(`/api/pdf`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    urls: urls,
                    docID: docID,
                }),
            });
            if (!response.ok) {
                throw new Error('Failed to call the API');
            }
        } catch (error) {
            console.error('Error in callChatAPI:', error);
            throw error;
        }
    }
    console.log(updatedData.id)

    const { data: updatedData2, error: updateError2 } = await supabase.from('profiles').update({documents: [...documents, updatedData.id]}).eq('id', id)

    await callChatAPI(url, updatedData.id)

}


api-route file (/api/pdf)

3 Replies

import { NextResponse } from "next/server";
import fetch from 'node-fetch';
import pdf from 'pdf-parse';
import { ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings } from "@langchain/google-genai";
import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
import { createClient } from "@/utils/supabase/server"

export async function POST(req: Request) {
  const apiKey = process.env.NEXT_GOOGLE_GEMINI_KEY;
  const supabase = createClient();

  try {
    const { urls, docID } = await req.json();

    if (!urls) {
      return NextResponse.json({ error: 'No valid URLs provided' }, { status: 400 });
    }

    const response = await fetch(urls);
    if (!response.ok) {
      throw new Error('Failed to fetch the URL');
    }

    const buffer = await response.arrayBuffer();
    if (!buffer) {
      throw new Error('Failed to read the buffer');
    }

    // Parse the PDF to extract text
    const data = await pdf(Buffer.from(buffer));
    if (!data) {
      throw new Error('Failed to parse the data');
    }
    const text = data.text;


    // Use LangChain's RecursiveCharacterTextSplitter to split the text
    const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 600, chunkOverlap: 100 });


    // ... (previous code remains the same)

const chunks = await splitter.createDocuments([text]);
if (!chunks || chunks.length === 0) {
  return NextResponse.json({ error: 'No valid PDFs were processed' }, { status: 400 });
}

const embeddings = new GoogleGenerativeAIEmbeddings({
  apiKey: apiKey,
  modelName: "embedding-004",
});

// Create an array to store all insert operations
const insertPromises = chunks.map(async (chunk, index) => {
  const embedding = await embeddings.embedQuery(chunk.pageContent);
  
  return supabase
    .from('vectors')
    .insert({
      document: docID,
      chunk_index: index,
      content: chunk.pageContent,
      embedding: embedding,
    });
});

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Failed to process PDFs' }, { status: 500 });
  }
}
help me plz 🙏🏼
i moved my api call to the client side and i get this error