Next.js Discord

Discord Forum

Is there a work around to avoid needing absolute url?

Answered
Carea Castellano Manchego posted this in #help-forum
Open in Discord
Carea Castellano ManchegoOP
So, i need to fetch from the api folder, but the url needs to be absolute to work.

so if i'm running the project locally, the fetch needs to be

const res = await fetch('http://localhost:3000/api/products')


i want to be:

const res = await fetch('/api/products')


How can i achieve this?
Answered by Asian black bear
If it's from server-side code, don't fetch your own API: https://nextjs-faq.com/fetch-api-in-rsc
View full answer

9 Replies

Asian black bear
If it's from client-side code just fetch /api/products (notice the prefixed /).
Asian black bear
If it's from server-side code, don't fetch your own API: https://nextjs-faq.com/fetch-api-in-rsc
Answer
Carea Castellano ManchegoOP
Sorry for the newbie question @Asian black bear , i don't want to be a pushover,

But how would that be applied here? If you could give a light, it would be very appreciated

I never used this prisma lib

//featuredProducts.tsx
import Slider from './Slider'
import { Product } from '../../../types'

export default async function FeaturedProducts() {
    const res = await fetch('http://localhost:3000/api/products')
    if (!res.ok) throw new Error('Failed to fetch data')

    const products: Product[] = await res.json()

    return (
        <div>
            <h2>Men's Clothing</h2>
            <Slider products={products.filter(p => p.category === 'men')} />

            <h2>Women's Clothing</h2>
            <Slider products={products.filter(p => p.category === "women's clothing")} />

            <h2>Accessories</h2>
            <Slider products={products.filter(p => p.category === 'accessories')} />
        </div>
    )
}


//route.ts

``import { NextResponse } from 'next/server' import mongoose from 'mongoose' import Product from '../../(models)/Products' export async function GET(request: Request) { try { if (mongoose.connection.readyState === 0) { await mongoose.connect(process.env.MONGODB_URI as string) } const products = await Product.find() console.log(products) return NextResponse.json(products) } catch (error) { console.error('Database fetch error:', error) return NextResponse.json({ error: 'Failed to fetch products' }, { status: 500 }) } }
Asian black bear
You just copy the logic that your current route handler does directly into the products component.
Overly simplified: const products = await Product.find()
Asian black bear
This is unrelated to your question of this thread, but I highly recommend you to drop using mongoose directly in the long run and instead use a proper ORM such as Drizzle or Prisma and replace Mongo with a proper relational database such as Postgres or MySQL. The former gives a better developer experience not having to deal with driver-specific details and the latter gives you a proper database because 99% of the people using Mongo don't understand why it's a terrible choice for pretty much anything.
Asian black bear
Mongo and document-based DBs in general are designed to dump fully unstructured data such as logs in there, nothing else. The moment you have relations you really should just use an RDBMS.
@Asian black bear You just copy the logic that your current route handler does directly into the products component.
Carea Castellano ManchegoOP
thank you so much, @Asian black bear it worked, but i'll redo all my code and drop the mongodb xD