Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js, interacting with a database through API routes vs doing it directly

Tags:

next.js

I am creating a Next.js application using Supabase as the backend service, but Firebase or MongoDB would be the same in this scenario. I have read several articles on Next.js API routes, and in some of them the interactions with the database are done using these routes, yet I still don't understand what is the difference between using an API route to interat with my database or just write these queries directly on my components, for example:

Inserting something into the database. I have a form that on submission, adds an item to the database:

const handleSubmit = async (e) => {
    e.preventDefault();
    ...

        const { data: itemData, error } = await supabase
            .from('items')
            .insert({
                username: user.username,
                title,
                description,
            })
            .select();
            ...
            

Or:

const handleSubmit = async (e) => {
    e.preventDefault();
    ...

        fetch('api/createItem', {
            method: 'POST',
            body: JSON.stringify(newItem),
            headers: {
                'Content-Type': 'application/json',
            },
        })
            .then((response) => response.json())
            .then((data) => console.log(data));

Then on the API route I would insert the item to the database. Both work, both do the same, is there any benefit on using an API route here or not at all? I have seen different articles using both never clarifying why it makes sense to use an API route to do this.

like image 218
Sergi Avatar asked Oct 27 '25 03:10

Sergi


1 Answers

So I understand the question as

"Why should I use NextJS API routes to communicate with the Supabase Restlike API, instead of calling it directly from client code?"

Just using the Supabase API directly would be easier to implement, when not using SSR with Nextjs. You just use the Supabase client and be done with it.

My opinionated take on this is: A restful API like Supabase exposes (which is actually Postgrest) is not a perfect fit for client application development. Its purpose is to provide a uniform way of performing crud operations with different clients. The complete API should not be made public to internet because it would increase the attack vector.

By using the NextJS API Routes (or use serverSideProps) you will get the chance to implement data fetching, that is more tailored to your application needs, rather trying to satisfy the shape of the API endpoints. You will also get an additional layer of security.

However: You will probably find yourself just proxying request to the API in many cases, and you will ask yourself: Why am I doing this not directly :D

like image 160
madflow Avatar answered Oct 30 '25 15:10

madflow