Home

Framework Quickstarts

Use Supabase with Next.js

Learn how to create a Supabase project, add some sample data to your database, and query the data from a Next.js app.

1

Set up a Supabase project with sample data

Create a new project in the Supabase Dashboard.

After your project is ready, create a table in your Supabase database using the SQL Editor in the Dashboard.

Use the following SQL statement to create a countries table with some sample data.

SQL_EDITOR

_10
-- Create the table
_10
create table countries (
_10
id serial primary key,
_10
name text not null
_10
);
_10
_10
-- Insert some sample data into the table
_10
insert into countries (name) values ('United States');
_10
insert into countries (name) values ('Canada');
_10
insert into countries (name) values ('Mexico');

2

Create a Next.js app

Use the create-next-app command and the with-supabase template, to create a Next.js app pre-configured with:

Terminal

_10
npx create-next-app -e with-supabase my-app && cd my-app

3

Declare Supabase Environment Variables

Rename .env.local.example to .env.local and populate with your project's URL and Anon Key.

.env.local

_10
NEXT_PUBLIC_SUPABASE_URL=your-project-url
_10
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key

4

Query Supabase data from Next.js

Create a new file at app/countries/page.tsx and populate with the following.

This will select all the rows from the countries table in Supabase and render them on the page.

app/countries/page.tsx

_16
import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
_16
import { cookies } from "next/headers";
_16
_16
export default async function Index() {
_16
const supabase = createServerComponentClient({ cookies });
_16
_16
const { data: countries } = await supabase.from("countries").select();
_16
_16
return (
_16
<ul className="my-auto text-foreground">
_16
{countries?.map((country) => (
_16
<li key={country.id}>{country.name}</li>
_16
))}
_16
</ul>
_16
);
_16
}

5

Start the app

Run the development server, go to http://localhost:3000/countries in a browser and you should see the list of countries.

Terminal

_10
npm run dev