Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/get-ppg-dev/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { context, trace } from "@opentelemetry/api";
import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
import { BasicTracerProvider } from "@opentelemetry/sdk-trace-base";
import { unstable_startServer } from '@prisma/dev'

context.setGlobalContextManager(new AsyncLocalStorageContextManager());
trace.setGlobalTracerProvider(new BasicTracerProvider());

async function main() {
const server = await unstable_startServer({
persistenceMode: 'stateless',
Expand Down
3 changes: 3 additions & 0 deletions .github/get-ppg-dev/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
"author": "",
"license": "ISC",
"dependencies": {
"@opentelemetry/api": "1.9.0",
"@opentelemetry/context-async-hooks": "2.2.0",
"@opentelemetry/sdk-trace-base": "2.2.0",
"@prisma/dev": "latest"
}
}
69 changes: 69 additions & 0 deletions .github/tests/orm/betterauth-astro/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/bin/bash

set -eu

echo "🔍 Starting test setup..."

echo "📂 Current working directory before REPO_ROOT: $(pwd)"
echo "📁 Listing contents:"
ls -la

REPO_ROOT="$(git rev-parse --show-toplevel)"
echo "📌 Detected repo root: $REPO_ROOT"

cd "$REPO_ROOT/orm/betterauth-astro"
echo "📂 Changed directory to: $(pwd)"

echo "📦 Installing test deps..."
npm install

# Go to Node script dir and install its deps
NODE_SCRIPT_DIR="../../.github/get-ppg-dev"
pushd "$NODE_SCRIPT_DIR" > /dev/null
npm install

# Start Prisma Dev server
LOG_FILE="./ppg-dev-url.log"
rm -f "$LOG_FILE"
touch "$LOG_FILE"

echo "🚀 Starting Prisma Dev in background..."
node index.js >"$LOG_FILE" &
NODE_PID=$!

# Wait for DATABASE_URL
echo "🔎 Waiting for Prisma Dev to emit DATABASE_URL..."
MAX_WAIT=60
WAITED=0
until grep -q '^prisma+postgres://' "$LOG_FILE"; do
sleep 1
WAITED=$((WAITED + 1))
if [ "$WAITED" -ge "$MAX_WAIT" ]; then
echo "❌ Timeout waiting for DATABASE_URL"
cat "$LOG_FILE"
kill "$NODE_PID" || true
exit 1
fi
done

DB_URL=$(grep '^prisma+postgres://' "$LOG_FILE" | tail -1)
export DATABASE_URL="$DB_URL"
echo "✅ DATABASE_URL: $DATABASE_URL"

popd > /dev/null

npm install
npx prisma migrate dev --name init --schema prisma/schema.prisma
npm run dev &
pid=$!

sleep 15

# check frontend
curl --fail 'http://localhost:4321/'


kill "$pid"
echo "🛑 App stopped (PID $pid)"
kill "$NODE_PID"
wait "$NODE_PID" || true
26 changes: 26 additions & 0 deletions orm/betterauth-astro/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# build output
dist/
# generated types
.astro/

# dependencies
node_modules/

# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*


# environment variables
.env
.env.production

# macOS-specific files
.DS_Store

# jetbrains setting folder
.idea/

/prisma/generated
106 changes: 106 additions & 0 deletions orm/betterauth-astro/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Better-Auth + Prisma example

This example shows how to implement **authentication** using [Better-Auth](https://better-auth.com/), [Astro](https://astro.build/) and [Prisma](https://www.prisma.io).

## Getting started

### 1. Download example and navigate into the project directory

Download this example:

```
npx try-prisma@latest --template orm/betterauth-astro
```

Then, navigate into the project directory:

```
cd betterauth-astro
```

<details><summary><strong>Alternative:</strong> Clone the entire repo</summary>

Clone this repository:

```
git clone git@github.com:prisma/prisma-examples.git --depth=1
```

Install npm dependencies:

```
cd prisma-examples/orm/betterauth-astro
npm install
```

</details>

Rename the `.env.example` file to `.env`

### 2. Create a Prisma Postgres instance

This example uses a [Prisma Postgres](https://prisma.io/postgres) database by default. To get started with the project, you will need to setup a Prisma Postgres connection string:

1. Set up a new Prisma Postgres instance in the [Prisma Data Platform Console](https://console.prisma.io) and copy the database connection URL.

2. Add your database url to the `.env`

That's it, your project is now configured to use Prisma Postgres!

### 3. Generate and migrate Prisma client

1. Run the following command to generate the Prisma Client. This is what you will be using to interact with your database.

```
npx prisma generate
```

2. Migrate the DB

```
npx prisma migrate dev --name init
```

### 4. Set up Better-Auth

1. Generate a Better-Auth secret

```
npx @better-auth/cli@latest secret
```

2. Add the secret to the `.env`.

3. (Optional) If running on a port other than 4321, add that url to the `trustedOrigins` field in `auth-client.ts`

```diff
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: 'postgresql',
}),
emailAndPassword: {
enabled: true,
},
+ trustedOrigins: ['http://localhost:4322'],
})
```

### 5. Start the development server

```
npm run dev
```

The server is now running at http://localhost:4321

## Switch to another database

If you want to try this example with another database rather than Prisma Postgres, refer to the [Databases](https://www.prisma.io/docs/orm/overview/databases) section in our documentation.

## Next steps

- Check out the [Prisma docs](https://www.prisma.io/docs)
- [Join our community on Discord](https://pris.ly/discord?utm_source=github&utm_medium=prisma_examples&utm_content=next_steps_section) to share feedback and interact with other users.
- [Subscribe to our YouTube channel](https://pris.ly/youtube?utm_source=github&utm_medium=prisma_examples&utm_content=next_steps_section) for live demos and video tutorials.
- [Follow us on X](https://pris.ly/x?utm_source=github&utm_medium=prisma_examples&utm_content=next_steps_section) for the latest updates.
- Report issues or ask [questions on GitHub](https://pris.ly/github?utm_source=github&utm_medium=prisma_examples&utm_content=next_steps_section).
5 changes: 5 additions & 0 deletions orm/betterauth-astro/astro.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// @ts-check
import { defineConfig } from 'astro/config';

// https://astro.build/config
export default defineConfig({});
22 changes: 22 additions & 0 deletions orm/betterauth-astro/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "better-auth-test",
"type": "module",
"version": "0.0.1",
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"@prisma/client": "^6.18.0",
"@prisma/extension-accelerate": "^2.0.2",
"astro": "^5.15.1",
"better-auth": "^1.3.29",
"dotenv": "^17.2.3"
},
"devDependencies": {
"prisma": "^6.18.0",
"tsx": "^4.20.6"
}
}
13 changes: 13 additions & 0 deletions orm/betterauth-astro/prisma.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { defineConfig } from "prisma/config";
import "dotenv/config";

export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
engine: "classic",
datasource: {
url: process.env.DATABASE_URL!,
},
});
75 changes: 75 additions & 0 deletions orm/betterauth-astro/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

generator client {
provider = "prisma-client"
output = "../prisma/generated"
}

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

model User {
id String @id
name String
email String
emailVerified Boolean @default(false)
image String?
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
sessions Session[]
accounts Account[]

@@unique([email])
@@map("user")
}

model Session {
id String @id
expiresAt DateTime
token String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
ipAddress String?
userAgent String?
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@unique([token])
@@map("session")
}

model Account {
id String @id
accountId String
providerId String
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
accessToken String?
refreshToken String?
idToken String?
accessTokenExpiresAt DateTime?
refreshTokenExpiresAt DateTime?
scope String?
password String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

@@map("account")
}

model Verification {
id String @id
identifier String
value String
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt

@@map("verification")
}
9 changes: 9 additions & 0 deletions orm/betterauth-astro/public/favicon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 16 additions & 0 deletions orm/betterauth-astro/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/// <reference path="../.astro/types.d.ts" />

declare namespace App {
interface Locals {
user: import("better-auth").User | null;
session: import("better-auth").Session | null;
}
}

interface ImportMetaEnv {
readonly DATABASE_URL: string;
}

interface ImportMeta {
readonly env: ImportMetaEnv;
}
5 changes: 5 additions & 0 deletions orm/betterauth-astro/src/lib/auth-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createAuthClient } from "better-auth/client";

export const authClient = createAuthClient();

export const { signIn, signUp, signOut } = authClient;
12 changes: 12 additions & 0 deletions orm/betterauth-astro/src/lib/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { betterAuth } from 'better-auth'
import { prismaAdapter } from 'better-auth/adapters/prisma'
import prisma from './prisma'

export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: 'postgresql',
}),
emailAndPassword: {
enabled: true,
},
})
7 changes: 7 additions & 0 deletions orm/betterauth-astro/src/lib/prisma.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { PrismaClient } from "../../prisma/generated/client";

const prisma = new PrismaClient({
datasourceUrl: import.meta.env.DATABASE_URL,
});

export default prisma;
Loading