Blog

NextJS Supabase Database Migration Guide

22 Dec 2023
By Denis

NextJS Supabase Database Migration Guide

In this guide, we will learn how to use Supabase migrations in your NextJS project.

Migrations are a way to keep track of changes to your database schema. It is very convenient to use migrations when you are working with a team of developers. Migrations allow you to keep track of changes to your database schema and apply them to your production database.

We assume that you already have a Supabase project and a NextJS project.

Install Supabase CLI

First, we need to install the Supabase CLI. You can do this by running the following command in your terminal:

npm i supabase --save-dev

Initialize Supabase locally

Next, we need to initialize Supabase locally. This will create a new database in your local environment. You can do this by running the following command in your terminal:

supabase init

This will create supabase folder in your project root directory. This folder will contain all the files related to your Supabase database including migrations.

Run local Supabase (this requires Docker):

supabase start

Connect local database to your Supabase project

First, login to your Supabase account using Supabase CLI:

supabase login

Next, connect your local database to your Supabase project:

supabase link --project-ref <reference-id>

You can find your Reference ID in your Supabase project settings page.

Fetch and apply migrations from remote to local

If you have any existing tables in your remote Supabase database, you can fetch them and apply them to your local database:

supabase db remote commit

This will create new migrations for your local database. You can find them in the supabase/migrations folder.

Local DB changes in Supabase Studio

You can change your local DB in Supabase Studio which is available at http://localhost:54323.

Create new migration and push it to remote

Create migrations for the local database:

supabase db diff --use-migra <name> -f <name>

Apply existing migrations to the production database:

supabase db push

Conclusion

In this guide, we learned how to use Supabase migrations in your NextJS project. We also learned how to connect your local database to your Supabase project and how to fetch and apply migrations from remote to local.

Launch your SaaS with our Supabase + NextJS Course

Learn how to create an AI-powered SaaS from scratch using Supabase and Next.js. We will guide you from zero to launch. What you will learn:

  • Stripe payments
  • Authentication with email/password and social logins
  • AI functionality: Chat, Langchain integration, OpenAI API streaming and more
  • How to setup emails, file storage, etc.