Home

Framework Quickstarts

Use Supabase with NextJS

Learn how to create a Supabase project, add some sample data to your database, and query the data from a NextJS 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.

Editor

_10
-- Create the table
_10
create table countries (
_10
id serial primary key,
_10
name varchar(255) 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 NextJS app

Create a Next.js app using the create-next-app command.

Terminal

_10
npx create-next-app my-app

3

Install the Supabase client library

The fastest way to get started is to use the supabase-js client library which provides a convenient interface for working with Supabase from a NextJS app.

Navigate to the NextJS app and install supabase-js.

Terminal

_10
cd my-app && npm install @supabase/supabase-js

4

Create the Supabase client

In the /lib directory of your Next.js app, create a file called supabaseClient.js and add the following code to initialize the Supabase client with your project URL and public API (anon) key.

lib/supabaseClient.js

_10
import { createClient } from '@supabase/supabase-js'
_10
_10
export const supabase = createClient('https://<project>.supabase.co', '<your-anon-key>')

5

Query data from the app

Use the getServerSideProps method to fetch the data server-side and display the query result as a simple list.

Replace the existing function in your index file in the pages directory with the following code.

app/index.js

_23
import { supabase } from './../lib/supabaseClient';
_23
_23
function Page({ countries }) {
_23
return (
_23
<ul>
_23
{countries.map((country) => (
_23
<li key={country.id}>{country.name}</li>
_23
))}
_23
</ul>
_23
);
_23
}
_23
_23
export async function getServerSideProps() {
_23
let { data } = await supabase.from('countries').select()
_23
_23
return {
_23
props: {
_23
countries: data
_23
},
_23
}
_23
}
_23
_23
export default Page;

6

Start the app

Start the app and go to http://localhost:3000 in a browser and you should see the list of countries.

Terminal

_10
npm run dev