Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Add code block language for syntax highlighting

dannykng10235c32b210
diff --git a/apps/docs/pages/guides/integrations/authsignal.mdx b/apps/docs/pages/guides/integrations/authsignal.mdx
index 250b822b483..65d83b22d01 100644
--- a/apps/docs/pages/guides/integrations/authsignal.mdx
+++ b/apps/docs/pages/guides/integrations/authsignal.mdx
@@ -61,7 +61,7 @@ cd supabase-authsignal-example
Create a `.env.local` file and enter the following values:
-```
+```sh
NEXT_PUBLIC_SUPABASE_URL=get-from-supabase-dashboard
NEXT_PUBLIC_SUPABASE_ANON_KEY=get-from-supabase-dashboard
AUTHSIGNAL_SECRET=get-from-authsignal-dashboard
@@ -84,19 +84,19 @@ npm run dev
Install the Supabase client and Auth helpers for Next.js:
-```
+```bash
npm install @supabase/supabase-js @supabase/auth-helpers-nextjs
```
Install the Authsignal Node.js client:
-```
+```bash
npm install @authsignal/node
```
Finally install 2 packages to help encrypt and serialize session data in cookies:
-```
+```bash
npm install @hapi/iron cookie
npm install --save-dev @types/cookie
```
@@ -105,18 +105,18 @@ npm install --save-dev @types/cookie
Add the following code to `/lib/authsignal.ts`:
-```
-import { Authsignal } from "@authsignal/node";
+```ts
+import { Authsignal } from '@authsignal/node'
-const secret = process.env.AUTHSIGNAL_SECRET;
+const secret = process.env.AUTHSIGNAL_SECRET
if (!secret) {
- throw new Error("AUTHSIGNAL_SECRET is undefined");
+ throw new Error('AUTHSIGNAL_SECRET is undefined')
}
-const redirectUrl = "http://localhost:3000/api/callback";
+const redirectUrl = 'http://localhost:3000/api/callback'
-export const authsignal = new Authsignal({ secret, redirectUrl });
+export const authsignal = new Authsignal({ secret, redirectUrl })
```
The `redirectUrl` here is a Next.js API route which Authsignal will redirect back to after an MFA challenge. We'll implement this below.
@@ -131,83 +131,72 @@ Next we will add some helper functions for managing cookies:
Add the following code to `/lib/cookies.ts`:
-```
-import Iron from "@hapi/iron";
-import { Session } from "@supabase/supabase-js";
-import { parse, serialize } from "cookie";
-import { NextApiRequest, NextApiResponse } from "next";
+```ts
+import Iron from '@hapi/iron'
+import { Session } from '@supabase/supabase-js'
+import { parse, serialize } from 'cookie'
+import { NextApiRequest, NextApiResponse } from 'next'
export async function setTempCookie(session: Session, res: NextApiResponse) {
- const token = await Iron.seal(session, TEMP_TOKEN_SECRET, Iron.defaults);
+ const token = await Iron.seal(session, TEMP_TOKEN_SECRET, Iron.defaults)
const cookie = serialize(TEMP_COOKIE, token, {
maxAge: session.expires_in,
httpOnly: true,
- secure: process.env.NODE_ENV === "production",
- path: "/",
- sameSite: "lax",
- });
+ secure: process.env.NODE_ENV === 'production',
+ path: '/',
+ sameSite: 'lax',
+ })
- res.setHeader("Set-Cookie", cookie);
+ res.setHeader('Set-Cookie', cookie)
}
-export async function getSessionFromTempCookie(
- req: NextApiRequest
-): Promise<Session | undefined> {
- const cookie = req.headers.cookie as string;
+export async function getSessionFromTempCookie(req: NextApiRequest): Promise<Session | undefined> {
+ const cookie = req.headers.cookie as string
- const cookies = parse(cookie ?? "");
+ const cookies = parse(cookie ?? '')
- const tempCookie = cookies[TEMP_COOKIE];
+ const tempCookie = cookies[TEMP_COOKIE]
if (!tempCookie) {
- return undefined;
+ return undefined
}
- const session = await Iron.unseal(
- tempCookie,
- TEMP_TOKEN_SECRET,
- Iron.defaults
- );
+ const session = await Iron.unseal(tempCookie, TEMP_TOKEN_SECRET, Iron.defaults)
- return session;
+ return session
}
export function setAuthCookie(session: Session, res: NextApiResponse) {
- const { access_token, refresh_token, expires_in } = session;
+ const { access_token, refresh_token, expires_in } = session
const authCookies = [
{ name: ACCESS_TOKEN_COOKIE, value: access_token },
- refresh_token
- ? { name: REFRESH_TOKEN_COOKIE, value: refresh_token }
- : undefined,
+ refresh_token ? { name: REFRESH_TOKEN_COOKIE, value: refresh_token } : undefined,
]
.filter(isDefined)
.map(({ name, value }) =>
serialize(name, value, {
maxAge: expires_in,
httpOnly: true,
- secure: process.env.NODE_ENV === "production",
- path: "/",
- sameSite: "lax",
+ secure: process.env.NODE_ENV === 'production',
+ path: '/',
+ sameSite: 'lax',
})
- );
+ )
// Also clear the temp cookie
- const updatedCookies = [
- ...authCookies,
- serialize(TEMP_COOKIE, "", { maxAge: -1, path: "/" }),
- ];
+ const updatedCookies = [...authCookies, serialize(TEMP_COOKIE, '', { maxAge: -1, path: '/' })]
- res.setHeader("Set-Cookie", updatedCookies);
+ res.setHeader('Set-Cookie', updatedCookies)
}
-const isDefined = <T>(value: T | undefined): value is T => !!value;
+const isDefined = <T>(value: T | undefined): value is T => !!value
-const TEMP_TOKEN_SECRET = process.env.TEMP_TOKEN_SECRET!;
-const TEMP_COOKIE = "as-mfa-cookie";
-const ACCESS_TOKEN_COOKIE = "sb-access-token";
-const REFRESH_TOKEN_COOKIE = "sb-refresh-token";
+const TEMP_TOKEN_SECRET = process.env.TEMP_TOKEN_SECRET!
+const TEMP_COOKIE = 'as-mfa-cookie'
+const ACCESS_TOKEN_COOKIE = 'sb-access-token'
+const REFRESH_TOKEN_COOKIE = 'sb-refresh-token'
```
## Step 7: Building the UI
@@ -216,34 +205,34 @@ We will add some form components for signing in and signing up as well as a basi
Add the following code to `/pages/sign-up.tsx`:
-```
-import Link from "next/link";
-import { useRouter } from "next/router";
+```ts
+import Link from 'next/link'
+import { useRouter } from 'next/router'
export default function SignUpPage() {
- const router = useRouter();
+ const router = useRouter()
return (
<main>
<form
onSubmit={async (e) => {
- e.preventDefault();
+ e.preventDefault()
const target = e.target as typeof e.target & {
- email: { value: string };
- password: { value: string };
- };
+ email: { value: string }
+ password: { value: string }
+ }
- const email = target.email.value;
- const password = target.password.value;
+ const email = target.email.value
+ const password = target.password.value
- await fetch("/api/sign-up", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
+ await fetch('/api/sign-up', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
- }).then((res) => res.json());
+ }).then((res) => res.json())
- router.push("/");
+ router.push('/')
}}
>
<label htmlFor="email">Email</label>
@@ -253,49 +242,49 @@ export default function SignUpPage() {
<button type="submit">Sign up</button>
</form>
<div>
- {"Already have an account? "}
+ {'Already have an account? '}
<Link href="sign-in">
<a>Sign in</a>
</Link>
</div>
</main>
- );
+ )
}
```
Then add the following code to `/pages/sign-in.tsx`:
-```
-import Link from "next/link";
-import { useRouter } from "next/router";
+```ts
+import Link from 'next/link'
+import { useRouter } from 'next/router'
export default function SignInPage() {
- const router = useRouter();
+ const router = useRouter()
return (
<main>
<form
onSubmit={async (e) => {
- e.preventDefault();
+ e.preventDefault()
const target = e.target as typeof e.target & {
- email: { value: string };
- password: { value: string };
- };
+ email: { value: string }
+ password: { value: string }
+ }
- const email = target.email.value;
- const password = target.password.value;
+ const email = target.email.value
+ const password = target.password.value
- const { state, mfaUrl } = await fetch("/api/sign-in", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
+ const { state, mfaUrl } = await fetch('/api/sign-in', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
- }).then((res) => res.json());
+ }).then((res) => res.json())
- if (state === "CHALLENGE_REQUIRED") {
- window.location.href = mfaUrl;
+ if (state === 'CHALLENGE_REQUIRED') {
+ window.location.href = mfaUrl
} else {
- router.push("/");
+ router.push('/')
}
}}
>
@@ -312,38 +301,38 @@ export default function SignInPage() {
</Link>
</div>
</main>
- );
+ )
}
```
Now we will use Supabase's `withPageAuth` wrapper around `getServerSideProps` to make the home page require authentication via SSR. Replace the existing code in `/pages/index.tsx` with the following:
-```
-import { getUser, User, withPageAuth } from "@supabase/auth-helpers-nextjs";
-import { GetServerSideProps } from "next";
-import { useRouter } from "next/router";
-import { authsignal } from "../lib/authsignal";
+```ts
+import { getUser, User, withPageAuth } from '@supabase/auth-helpers-nextjs'
+import { GetServerSideProps } from 'next'
+import { useRouter } from 'next/router'
+import { authsignal } from '../lib/authsignal'
interface Props {
- user: User;
- isEnrolled: boolean;
+ user: User
+ isEnrolled: boolean
}
export const getServerSideProps: GetServerSideProps<Props> = withPageAuth({
- redirectTo: "/sign-in",
+ redirectTo: '/sign-in',
async getServerSideProps(ctx) {
- const { user } = await getUser(ctx);
+ const { user } = await getUser(ctx)
- const { isEnrolled } = await authsignal.getUser({userId: user.id});
+ const { isEnrolled } = await authsignal.getUser({ userId: user.id })
return {
props: { user, isEnrolled },
- };
+ }
},
-});
+})
export default function HomePage({ user, isEnrolled }: Props) {
- const router = useRouter();
+ const router = useRouter()
return (
<main>
@@ -351,29 +340,29 @@ export default function HomePage({ user, isEnrolled }: Props) {
<div> Signed in as: {user?.email}</div>
<button
onClick={async (e) => {
- e.preventDefault();
+ e.preventDefault()
- const { mfaUrl } = await fetch("/api/mfa", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
+ const { mfaUrl } = await fetch('/api/mfa', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ isEnrolled }),
- }).then((res) => res.json());
+ }).then((res) => res.json())
- window.location.href = mfaUrl;
+ window.location.href = mfaUrl
}}
>
- {isEnrolled ? "Manage MFA settings" : "Set up MFA"}
+ {isEnrolled ? 'Manage MFA settings' : 'Set up MFA'}
</button>
- <button onClick={() => router.push("/api/sign-out")}>Sign out</button>
+ <button onClick={() => router.push('/api/sign-out')}>Sign out</button>
</section>
</main>
- );
+ )
}
```
Optional: To make things look a bit nicer, you can add the following to `/styles/globals.css`:
-```
+```css
main {
min-height: 100vh;
display: flex;
@@ -435,113 +424,95 @@ Now we'll replace the existing api routes in `/pages/api/` with 5 new routes:
Add the following code to `/pages/api/sign-in.ts`:
-```
-import { supabaseClient } from "@supabase/auth-helpers-nextjs";
-import { NextApiRequest, NextApiResponse } from "next";
-import { authsignal } from "../../lib/authsignal";
-import { setAuthCookie, setTempCookie } from "../../lib/cookies";
-
-export default async function signIn(
- req: NextApiRequest,
- res: NextApiResponse
-) {
- const { email, password } = req.body;
-
- const { data, error } = await supabaseClient.auth.api.signInWithEmail(
- email,
- password
- );
+```ts
+import { supabaseClient } from '@supabase/auth-helpers-nextjs'
+import { NextApiRequest, NextApiResponse } from 'next'
+import { authsignal } from '../../lib/authsignal'
+import { setAuthCookie, setTempCookie } from '../../lib/cookies'
+
+export default async function signIn(req: NextApiRequest, res: NextApiResponse) {
+ const { email, password } = req.body
+
+ const { data, error } = await supabaseClient.auth.api.signInWithEmail(email, password)
if (error || !data?.user) {
- return res.send({ error });
+ return res.send({ error })
}
const { state, url: mfaUrl } = await authsignal.track({
- action: "signIn",
+ action: 'signIn',
userId: data.user.id,
- });
+ })
- if (state === "CHALLENGE_REQUIRED") {
- await setTempCookie(data, res);
+ if (state === 'CHALLENGE_REQUIRED') {
+ await setTempCookie(data, res)
} else {
- setAuthCookie(data, res);
+ setAuthCookie(data, res)
}
- res.send({ state, mfaUrl });
+ res.send({ state, mfaUrl })
}
```
Then to handle new sign-ups add the following to `/pages/api/sign-up.ts`:
-```
-import { supabaseClient } from "@supabase/auth-helpers-nextjs";
-import { Session } from "@supabase/supabase-js";
-import { NextApiRequest, NextApiResponse } from "next";
-import { setAuthCookie } from "../../lib/cookies";
-
-export default async function signUp(
- req: NextApiRequest,
- res: NextApiResponse
-) {
- const { email, password } = req.body;
-
- const { data, error } = await supabaseClient.auth.api.signUpWithEmail(
- email,
- password
- );
+```ts
+import { supabaseClient } from '@supabase/auth-helpers-nextjs'
+import { Session } from '@supabase/supabase-js'
+import { NextApiRequest, NextApiResponse } from 'next'
+import { setAuthCookie } from '../../lib/cookies'
+
+export default async function signUp(req: NextApiRequest, res: NextApiResponse) {
+ const { email, password } = req.body
+
+ const { data, error } = await supabaseClient.auth.api.signUpWithEmail(email, password)
if (error || !isSession(data)) {
- res.send({ error });
+ res.send({ error })
} else {
- setAuthCookie(data, res);
- res.send({ data });
+ setAuthCookie(data, res)
+ res.send({ data })
}
}
-const isSession = (data: any): data is Session => !!data?.access_token;
+const isSession = (data: any): data is Session => !!data?.access_token
```
To clear the auth cookies on sign-out add the following to `/pages/api/sign-out.ts`:
-```
-import { supabaseClient } from "@supabase/auth-helpers-nextjs";
-import { NextApiRequest, NextApiResponse } from "next";
-
-export default async function signOut(
- req: NextApiRequest,
- res: NextApiResponse
-) {
- supabaseClient.auth.api.deleteAuthCookie(req, res, { redirectTo: "/sign-in" });
+```ts
+import { supabaseClient } from '@supabase/auth-helpers-nextjs'
+import { NextApiRequest, NextApiResponse } from 'next'
+
+export default async function signOut(req: NextApiRequest, res: NextApiResponse) {
+ supabaseClient.auth.api.deleteAuthCookie(req, res, { redirectTo: '/sign-in' })
}
```
To handle the user's actions to set up MFA or manage their existing MFA settings, add the following to `/pages/api/mfa.ts`:
-```
-import { getUser, withApiAuth } from "@supabase/auth-helpers-nextjs";
-import { NextApiRequest, NextApiResponse } from "next";
-import { authsignal } from "../../lib/authsignal";
-
-export default withApiAuth(async function mfa(
- req: NextApiRequest,
- res: NextApiResponse
-) {
- if (req.method !== "POST") {
- return res.status(405).send({ message: "Only POST requests allowed" });
+```ts
+import { getUser, withApiAuth } from '@supabase/auth-helpers-nextjs'
+import { NextApiRequest, NextApiResponse } from 'next'
+import { authsignal } from '../../lib/authsignal'
+
+export default withApiAuth(async function mfa(req: NextApiRequest, res: NextApiResponse) {
+ if (req.method !== 'POST') {
+ return res.status(405).send({ message: 'Only POST requests allowed' })
}
- const { user } = await getUser({ req, res });
+ const { user } = await getUser({ req, res })
- const { isEnrolled } = req.body;
+ const { isEnrolled } = req.body
const { url: mfaUrl } = await authsignal.track({
- action: isEnrolled ? "manageSettings" : "enroll",
+ action: isEnrolled ? 'manageSettings' : 'enroll',
userId: user.id,
redirectToSettings: isEnrolled,
- });
+ })
- res.send({ mfaUrl });
-});
+ res.send({ mfaUrl })
+})
```
Because the user should be authenticated with Supabase to set up or manage MFA, we can use Supabase's `withApiAuth` wrapper to protect this route.
@@ -550,28 +521,25 @@ The `redirectToSettings` param specifies whether the user should be redirected t
Finally we need a route to handle the redirect back from Authsignal after an MFA challenge. Add the following to `/pages/api/callback.ts`:
-```
-import { NextApiRequest, NextApiResponse } from "next";
-import { authsignal } from "../../lib/authsignal";
-import { getSessionFromTempCookie, setAuthCookie } from "../../lib/cookies";
+```ts
+import { NextApiRequest, NextApiResponse } from 'next'
+import { authsignal } from '../../lib/authsignal'
+import { getSessionFromTempCookie, setAuthCookie } from '../../lib/cookies'
-export default async function callback(
- req: NextApiRequest,
- res: NextApiResponse
-) {
- const token = req.query.token as string;
+export default async function callback(req: NextApiRequest, res: NextApiResponse) {
+ const token = req.query.token as string
- const { success } = await authsignal.validateChallenge({ token });
+ const { success } = await authsignal.validateChallenge({ token })
if (success) {
- const session = await getSessionFromTempCookie(req);
+ const session = await getSessionFromTempCookie(req)
if (session) {
- setAuthCookie(session, res);
+ setAuthCookie(session, res)
}
}
- res.redirect("/");
+ res.redirect('/')
}
```