#How to fetch API from app/api folder?

9 messages · Page 1 of 1 (latest)

tropic mica
#

I'm using the app directory in the latest version of NextJS. I created the api folder inside of app/api/hello/route.ts where i have a route
w/ following code

export async function GET(){
    return new Response('Hello World')
}

inside app directory i have a page called page.tsx w/ following code

import Image from 'next/image'

export default async function Home() {
  const req = await fetch('/api/hello')
  const data  = await req.json()

  return (
    <>
    {JSON.stringify(data)}
    </>
  )
}

when i run my app i get Error: Failed to parse URL from /api/hello why is this happening

tropic mica
#

I had to fetch the URL before the route...

const req = await fetch('http://localhost:3000/api/hello')

#

!closed

#

!close

trim dagger
#

Did you manage to build it?

tropic mica
# trim dagger Did you manage to build it?

Yes j ended up deploying and then using a ternary if process.env.NODE_ENV === ‘production’ : “deployed url” : “local host url”
Const req = await fetch(url/api/hello)

trim dagger
#

Did you deploy it to Vercel (or elsewhere)?

#

I'm asking because I'm having the same problem with deploying, and it looks like it's not even possible?

#

Because at build time the /api/hello route isn't running so it can't be fetched from a server component