Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(examples): Next.js + Better Auth #2750

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
27 changes: 27 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,33 @@ updates:
- dependency-name: eslint
versions: [">=9"]

- package-ecosystem: npm
directory: /examples/nextjs-better-auth
schedule:
# Our dependencies should be checked daily
interval: daily
assignees:
- blaine-arcjet
- e-moran
reviewers:
- blaine-arcjet
- e-moran
commit-message:
prefix: deps(example)
prefix-development: deps(example)
groups:
dependencies:
patterns:
- "*"
ignore:
# Ignore updates to the @types/node package due to conflict between
# Headers in DOM.
- dependency-name: "@types/node"
versions: [">18.18"]
# TODO(#539): Upgrade to eslint 9
- dependency-name: eslint
versions: [">=9"]

- package-ecosystem: npm
directory: /examples/nextjs-bot-categories
schedule:
Expand Down
6 changes: 6 additions & 0 deletions examples/nextjs-better-auth/.env.local.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
ARCJET_KEY=
BETTER_AUTH_SECRET=
BETTER_AUTH_URL=http://localhost:3000 #Base URL of your app
# See https://www.better-auth.com/docs/authentication/github
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
3 changes: 3 additions & 0 deletions examples/nextjs-better-auth/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
38 changes: 38 additions & 0 deletions examples/nextjs-better-auth/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

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

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts

sqlite.db
50 changes: 50 additions & 0 deletions examples/nextjs-better-auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<a href="https://arcjet.com" target="_arcjet-home">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://arcjet.com/logo/arcjet-dark-lockup-voyage-horizontal.svg">
<img src="https://arcjet.com/logo/arcjet-light-lockup-voyage-horizontal.svg" alt="Arcjet Logo" height="128" width="auto">
</picture>
</a>

# Arcjet bot detection with Next.js + Better Auth

This example shows how to use Arcjet with [Better
Auth](https://www.better-auth.com). Arcjet is implemented as a hook in
`auth.ts`, which is our recommended approach.

Alternatively, you can use the Arcjet integration in
`app/api/auth/[...all]/route.ts`. If you do, remove the hook from `auth.ts` to
avoid duplicate protection.

## How to use

1. From the root of the project, install the SDK dependencies.

```bash
npm ci
```

2. Enter this directory and install the example's dependencies.

```bash
cd examples/nextjs-app-dir-rate-limit
npm ci
```

3. Rename `.env.local.example` to `.env.local` and add your Arcjet key and a
secret for Better Auth. You will need to [create a GitHub OAuth
app](https://github.com/settings/applications) for testing (see the [Better
Auth docs](https://www.better-auth.com/docs/authentication/github)).

4. Start the dev server.

```bash
npm run dev
```

5. Run the database migration. A SQLite database is used for this example.

```bash
npx @better-auth/cli migrate
```

6. Visit `http://localhost:3000`.
84 changes: 84 additions & 0 deletions examples/nextjs-better-auth/app/api/auth/[...all]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// This is an alternative to our recommended approach of implementing the Arcjet
// as a Better Auth hook. Choose one or the other to avoid duplicate
// protections.

import { auth } from "@/auth";
//import ip from "@arcjet/ip";
//import arcjet, { shield, tokenBucket } from "@arcjet/next";
import { toNextJsHandler } from "better-auth/next-js";
//import { NextRequest } from "next/server";

export const { POST, GET } = toNextJsHandler(auth);

/*
// The arcjet instance is created outside of the handler
const aj = arcjet({
key: process.env.ARCJET_KEY!, // Get your site key from https://app.arcjet.com
characteristics: ["userId"],
rules: [
// Protect against common attacks with Arcjet Shield
shield({
mode: "LIVE", // will block requests. Use "DRY_RUN" to log only
}),
// Create a token bucket rate limit. Other algorithms are supported.
tokenBucket({
mode: "LIVE", // will block requests. Use "DRY_RUN" to log only
refillRate: 5, // refill 5 tokens per interval
interval: 10, // refill every 10 seconds
capacity: 50, // bucket maximum capacity of 10 tokens
}),
],
});

const betterAuthHandlers = toNextJsHandler(auth.handler);

const ajProtectedPOST = async (req: NextRequest) => {
const session = await auth.api.getSession({
headers: await req.headers,
})

// If the user is logged in we'll use their ID as the identifier. This
// allows limits to be applied across all devices and sessions (you could
// also use the session ID). Otherwise, fall back to the IP address.
let userId: string;
if (session?.user.id) {
userId = session.user.id;
} else {
userId = ip(req) || "127.0.0.1"; // Fall back to local IP if none
}

// Deduct 5 tokens from the token bucket
const decision = await aj.protect(req, { userId, requested: 5 });

console.log("Arcjet Decision:", decision);

if (decision.isDenied()) {
if (decision.reason.isRateLimit()) {
return Response.json(
{
error: "Rate Limit Exceeded",
reason: decision.reason,
},
{
status: 429,
}
);
} else {
return Response.json(
{
error: "Forbidden",
reason: decision.reason,
},
{
status: 403,
}
);
}
} else {
return betterAuthHandlers.POST(req);
}
}

export { ajProtectedPOST as POST };
export const { GET } = betterAuthHandlers;
*/
18 changes: 18 additions & 0 deletions examples/nextjs-better-auth/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { Metadata } from 'next'

export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}

export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
26 changes: 26 additions & 0 deletions examples/nextjs-better-auth/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { auth } from "@/auth"
import { headers } from "next/headers"
import SignInButton from '@/components/SignInGitHub'
import SignOutButton from "@/components/SignOut"
import SignUp from "@/components/SignUp"

export default async function Home() {
const session = await auth.api.getSession({
headers: await headers()
})

if (!session) {
return (
<>
<div>Not authenticated. <SignInButton /> or sign up below.</div>
<div><SignUp /></div>
</>
)
}

return (
<div>
<h1>Welcome {session.user.name}. <SignOutButton /></h1>
</div>
)
}
5 changes: 5 additions & 0 deletions examples/nextjs-better-auth/auth-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createAuthClient } from "better-auth/react" // make sure to import from better-auth/react

export const authClient = createAuthClient({
//you can pass client configuration here
})
Loading
Loading