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.
>Solution :
There are a few benefits to using an API route to interact with your database:
-
Separation of concerns: By using an API route to handle database interactions, you can separate the logic for interacting with the database from the logic for rendering the UI of your application. This can make your code easier to understand and maintain.
-
Reusability: If you have multiple components that need to perform the same database operation (e.g. inserting an item), you can reuse the API route instead of duplicating the database code in each component.
-
API versioning: If you want to make changes to the way your application interacts with the database, you can do so by updating the API route without having to update every component that uses the route. This can be especially useful if you have a large application with many components that use the API route.
-
Security: By using an API route to interact with the database, you can add security measures such as authentication and authorization to ensure that only authorized users can perform certain operations.
In short, using an API route to interact with the database can make your code more modular, reusable, and maintainable. However, it’s also important to consider the complexity of your application and the trade-offs between simplicity and scalability when deciding whether to use an API route or not.