DEV Community

Akhmad Rizki Prayoga
Akhmad Rizki Prayoga

Posted on

Setup Astro With Supabase and Prisma

First, you must Install Astro on your Laptop or PC. You can run this command on your terminal npm create astro@latest. before that, you must have NodeJs version min. v18.17.1 or v20.3.0. If your version is v19 please upgrade to v20 because v19 is not supported πŸ₯².

After that, you just name it your project whatever you want.
Oke, if installation is already finished. Next, you just install the Supabase dependencies on your Astro Project. We just run this command on your terminal npm install @supabase/supabase-js

The next step is to update .env file and env.d.ts

.env file
---
SUPABASE_URL=""
SUPABASE_ANON_KEY=""
DATABASE_URL=""
DIRECT_URL=""
Enter fullscreen mode Exit fullscreen mode
src/env.d.ts
---
...
interface ImportMetaEnv {
  readonly SUPABASE_URL: string;
  readonly SUPABASE_ANON_KEY: string;
  readonly DATABASE_URL: string;
}

interface ImportMeta {
  readonly env: ImportMetaEnv;
}
Enter fullscreen mode Exit fullscreen mode

actually, the two files above are automatically added from the first time you create the project.

Then you can make a folder lib inside src then make a file supabase.ts

Image description

then put this code inside the file

import { createClient } from "@supabase/supabase-js";

export const supabase = createClient(
  import.meta.env.SUPABASE_URL,
  import.meta.env.SUPABASE_ANON_KEY
);

Enter fullscreen mode Exit fullscreen mode

Oke, next you must have SUPABASE_URL etc, so you can signup/sign-in on Supabase
If you have already logged in Supabase next you just Create a Project

Image description

To get supabase_url anon_key and database_url you just go to Project Setting like this

Image description

Go to Database Tab then copy the Connection String

Image description
You just change [YOUR-PASSWORD] to your database password.
the thing you need to pay attention to is on the tab Mode is chosen Transaction
Image description
then you must add ?pgbouncer=true&connection_limit=1 in the last of Database Url. So the final URL like this
postgresql://postgres.ojusknxqhzlydwyioarw:[YOUR-PASSWORD]@aws-0-ap-southeast-1.pooler.supabase.com:6543/postgres?pgbouncer=true&connection_limit=1

To get DIRECT_URL you just change Mode from Transaction to Session then you just copy

Image description


Next, to get the SUPABASE_URL and SUPABASE_ANON_KEY you just click API menu from the sidebar then copy Project Url for SUPABASE_URL and Project API Keys, anon, public for SUPABASE_ANON_KEY

Image description

Remember, all the credentials you must set for the best practice in .env file


Congratulation!! Your Astro project is successfully connected with Supabase. But before that, you must make sure that all is well.
The way is to create a table directly from Supabase.

You just go to the Database tab in the sidebar and click that

Image description

after that, click the table. then create a new table

Image description

for the default, column ID and createdAt is already set. You just add a column whatever you want.
For learning purposes, uncheck the enable the RLS

Image description


The next is go to index.astro file then adjust a little bit like this for test store data to Supabase.

---
import Layout from '../layouts/Layout.astro';
import Card from '../components/Card.astro';

import { supabase } from '../lib/supabase';

const { data, error } = await supabase
  .from('posts') // this your database name
  .insert({ title: 'This Title', description: 'this description' })
  .select()

console.log(data, error);
---
Enter fullscreen mode Exit fullscreen mode

Check your console or you just see in Supabase Database from they Dashboard site, make sure the data has been entered.

You can see the database configuration from Supabase documentation here

if successfully entered, next try to show in the browser.
Modify index.astro file again

---
import Layout from '../layouts/Layout.astro';
import Card from '../components/Card.astro';

import { supabase } from '../lib/supabase';

const { data, error } = await supabase
  .from('posts')
  .select()
---

<Layout title="Welcome to Astro.">
    <main>
        <h1>Welcome to <span class="text-gradient">Astro</span></h1>
        <ul role="list" class="link-card-grid">
            {data?.map((post) => (
                <Card
                    href={`/post/${post.id}`}
                    title={post.title}
                    body={post.description}
                />
            ))}
        </ul>
    </main>
</Layout>

Enter fullscreen mode Exit fullscreen mode

Oke, Congratulations you can store and show data from Supabase in your Astro project πŸŽ‰

NEXT!!!
We can try to use Prisma for the ORM in this project.

First, install the prisma in your Astro project, run this command in your terminal npx prisma then npx prisma init

after finish, you will see the Prisma folder in your project.
Open the schema.prisma then make the model, like example

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider  = "postgresql"
  url       = env("DATABASE_URL")
  directUrl = env("DIRECT_URL")
}

model posts {
  id          Int      @id @default(autoincrement())
  title       String
  description String
  createdAt   DateTime @default(now())
}
Enter fullscreen mode Exit fullscreen mode

after that run this command to generate a migration
npx prisma migrate dev --name init


Update the index.astro file

---
import Layout from '../layouts/Layout.astro';
import Card from '../components/Card.astro';

import { supabase } from '../lib/supabase';

import {PrismaClient} from '@prisma/client';
const prisma = new PrismaClient();

// get all tags
const posts = await prisma.tag.findMany();
---

<Layout title="Welcome to Astro.">
    <main>
        <h1>Welcome to <span class="text-gradient">Astro</span></h1>
        <ul role="list" class="link-card-grid">
            {posts?.map((post) => (
                <Card
                    href={`/post/${post.id}`}
                    title={post.title}
                    body={post.description}
                />
            ))}
        </ul>
    </main>
</Layout>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)