2024-09-09 web, development, javascript
API Route in Next.js 14 for Database Updates with Supabase
By O. Wolfson
Let's explore how to set up an API route using Next.js 14 that interacts with a database using Supabase. This setup involves creating a backend API route in a Next.js application to handle POST requests for updating a database and retrieving the status of these updates. We will go through the entire process step-by-step, from initializing the Supabase client to defining the API route. Note that I am using the app router in this example.
Prerequisites
To follow along with this tutorial, you should have:
- Node.js installed on your system.
- Basic knowledge of JavaScript and Next.js.
- A Supabase account, which you can set up at Supabase.
Step 1: Setting Up Your Next.js Project
If you haven't already created a Next.js project, you can start by setting one up using the following commands:
This sets up a new Next.js project in the my-next-app
directory.
Step 2: Adding Supabase to the Project
-
Install the Supabase JS Client:
Run the following command to install the Supabase client:
-
Configure Environment Variables:
Create a
.env.local
file in the root of your project and add the following environment variables:NEXT_PUBLIC_SUPABASE_URL=your_supabase_url NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
Replace
your_supabase_url
andyour_supabase_anon_key
with the actual values from your Supabase project settings.
Step 3: Creating the Supabase Client
Create a file named supabaseClient.js
in the root directory and add the following code to initialize the Supabase client:
Step 4: Writing the Database Update Function
In the lib
directory, create a file named update-database.mjs
and add the following function:
This function inserts the current date and time into a table called _update_database
.
the schema for the _update_database
table can be:
- id (int8): Unique identifier for each record
- update (Timestamp): Timestamp of the update
Step 5: Creating the API Route
Create a folder named api
within the app
directory and add a file named route.ts
. Add the following code to route.ts
handle POST requests:
Step 6: Testing the Setup
To test your API, you can use tools like Postman or simply use curl
:
You should see a response indicating the request was processed successfully or an error message.