Unverified Commit 2b7a2591 authored by Ivan Vasilov's avatar Ivan Vasilov Committed by GitHub

chore: Update the `with-supabase` example to use the Supabase Auth block (#78913)

This PR updates the `with-supabase` template to better auth pages,
Tailwind v4 and newest `components.json` for full compatibility with
shadcn/ui.

The `(auth-pages)` folder has been removed. For auth, the template is
now using the [password based auth
block](https://supabase.com/ui/docs/nextjs/password-based-auth) from the
Supabase UI Library which makes it easier to update it and keep it
up-to-date.

---------
Co-authored-by: 's avatarLee Robinson <lee@leerob.com>
parent ea1a76a6
...@@ -28,8 +28,9 @@ ...@@ -28,8 +28,9 @@
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
.pnpm-debug.log*
# local env files # env files (can opt-in for committing if needed)
.env*.local .env*.local
.env .env
......
...@@ -27,6 +27,7 @@ ...@@ -27,6 +27,7 @@
- Server - Server
- It just works! - It just works!
- supabase-ssr. A package to configure Supabase Auth to use cookies - supabase-ssr. A package to configure Supabase Auth to use cookies
- Password-based authentication block installed via the [Supabase UI Library](https://supabase.com/ui/docs/nextjs/password-based-auth)
- Styling with [Tailwind CSS](https://tailwindcss.com) - Styling with [Tailwind CSS](https://tailwindcss.com)
- Components with [shadcn/ui](https://ui.shadcn.com/) - Components with [shadcn/ui](https://ui.shadcn.com/)
- Optional deployment with [Supabase Vercel Integration and Vercel deploy](#deploy-your-own) - Optional deployment with [Supabase Vercel Integration and Vercel deploy](#deploy-your-own)
...@@ -79,7 +80,7 @@ If you wish to just develop locally and not deploy to Vercel, [follow the steps ...@@ -79,7 +80,7 @@ If you wish to just develop locally and not deploy to Vercel, [follow the steps
NEXT_PUBLIC_SUPABASE_ANON_KEY=[INSERT SUPABASE PROJECT API ANON KEY] NEXT_PUBLIC_SUPABASE_ANON_KEY=[INSERT SUPABASE PROJECT API ANON KEY]
``` ```
Both `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_ANON_KEY` can be found in [your Supabase project's API settings](https://app.supabase.com/project/_/settings/api) Both `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_ANON_KEY` can be found in [your Supabase project's API settings](https://supabase.com/dashboard/project/_?showConnect=true)
5. You can now run the Next.js local development server: 5. You can now run the Next.js local development server:
......
import { forgotPasswordAction } from "@/app/actions";
import { FormMessage, Message } from "@/components/form-message";
import { SubmitButton } from "@/components/submit-button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import Link from "next/link";
import { SmtpMessage } from "../smtp-message";
export default async function ForgotPassword(props: {
searchParams: Promise<Message>;
}) {
const searchParams = await props.searchParams;
return (
<>
<form className="flex-1 flex flex-col w-full gap-2 text-foreground [&>input]:mb-6 min-w-64 max-w-64 mx-auto">
<div>
<h1 className="text-2xl font-medium">Reset Password</h1>
<p className="text-sm text-secondary-foreground">
Already have an account?{" "}
<Link className="text-primary underline" href="/sign-in">
Sign in
</Link>
</p>
</div>
<div className="flex flex-col gap-2 [&>input]:mb-3 mt-8">
<Label htmlFor="email">Email</Label>
<Input name="email" placeholder="you@example.com" required />
<SubmitButton formAction={forgotPasswordAction}>
Reset Password
</SubmitButton>
<FormMessage message={searchParams} />
</div>
</form>
<SmtpMessage />
</>
);
}
export default async function Layout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="max-w-7xl flex flex-col gap-12 items-start">{children}</div>
);
}
import { signInAction } from "@/app/actions";
import { FormMessage, Message } from "@/components/form-message";
import { SubmitButton } from "@/components/submit-button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import Link from "next/link";
export default async function Login(props: { searchParams: Promise<Message> }) {
const searchParams = await props.searchParams;
return (
<form className="flex-1 flex flex-col min-w-64">
<h1 className="text-2xl font-medium">Sign in</h1>
<p className="text-sm text-foreground">
Don't have an account?{" "}
<Link className="text-foreground font-medium underline" href="/sign-up">
Sign up
</Link>
</p>
<div className="flex flex-col gap-2 [&>input]:mb-3 mt-8">
<Label htmlFor="email">Email</Label>
<Input name="email" placeholder="you@example.com" required />
<div className="flex justify-between items-center">
<Label htmlFor="password">Password</Label>
<Link
className="text-xs text-foreground underline"
href="/forgot-password"
>
Forgot Password?
</Link>
</div>
<Input
type="password"
name="password"
placeholder="Your password"
required
/>
<SubmitButton pendingText="Signing In..." formAction={signInAction}>
Sign in
</SubmitButton>
<FormMessage message={searchParams} />
</div>
</form>
);
}
import { signUpAction } from "@/app/actions";
import { FormMessage, Message } from "@/components/form-message";
import { SubmitButton } from "@/components/submit-button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import Link from "next/link";
import { SmtpMessage } from "../smtp-message";
export default async function Signup(props: {
searchParams: Promise<Message>;
}) {
const searchParams = await props.searchParams;
if ("message" in searchParams) {
return (
<div className="w-full flex-1 flex items-center h-screen sm:max-w-md justify-center gap-2 p-4">
<FormMessage message={searchParams} />
</div>
);
}
return (
<>
<form className="flex flex-col min-w-64 max-w-64 mx-auto">
<h1 className="text-2xl font-medium">Sign up</h1>
<p className="text-sm text text-foreground">
Already have an account?{" "}
<Link className="text-primary font-medium underline" href="/sign-in">
Sign in
</Link>
</p>
<div className="flex flex-col gap-2 [&>input]:mb-3 mt-8">
<Label htmlFor="email">Email</Label>
<Input name="email" placeholder="you@example.com" required />
<Label htmlFor="password">Password</Label>
<Input
type="password"
name="password"
placeholder="Your password"
minLength={6}
required
/>
<SubmitButton formAction={signUpAction} pendingText="Signing up...">
Sign up
</SubmitButton>
<FormMessage message={searchParams} />
</div>
</form>
<SmtpMessage />
</>
);
}
import { ArrowUpRight, InfoIcon } from "lucide-react";
import Link from "next/link";
export function SmtpMessage() {
return (
<div className="bg-muted/50 px-5 py-3 border rounded-md flex gap-4">
<InfoIcon size={16} className="mt-0.5" />
<div className="flex flex-col gap-1">
<small className="text-sm text-secondary-foreground">
<strong> Note:</strong> Emails are rate limited. Enable Custom SMTP to
increase the rate limit.
</small>
<div>
<Link
href="https://supabase.com/docs/guides/auth/auth-smtp"
target="_blank"
className="text-primary/50 hover:text-primary flex items-center text-sm gap-1"
>
Learn more <ArrowUpRight size={14} />
</Link>
</div>
</div>
</div>
);
}
"use server";
import { encodedRedirect } from "@/utils/utils";
import { createClient } from "@/utils/supabase/server";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
export const signUpAction = async (formData: FormData) => {
const email = formData.get("email")?.toString();
const password = formData.get("password")?.toString();
const supabase = await createClient();
const origin = (await headers()).get("origin");
if (!email || !password) {
return encodedRedirect(
"error",
"/sign-up",
"Email and password are required",
);
}
const { error } = await supabase.auth.signUp({
email,
password,
options: {
emailRedirectTo: `${origin}/auth/callback`,
},
});
if (error) {
console.error(error.code + " " + error.message);
return encodedRedirect("error", "/sign-up", error.message);
} else {
return encodedRedirect(
"success",
"/sign-up",
"Thanks for signing up! Please check your email for a verification link.",
);
}
};
export const signInAction = async (formData: FormData) => {
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const supabase = await createClient();
const { error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
return encodedRedirect("error", "/sign-in", error.message);
}
return redirect("/protected");
};
export const forgotPasswordAction = async (formData: FormData) => {
const email = formData.get("email")?.toString();
const supabase = await createClient();
const origin = (await headers()).get("origin");
const callbackUrl = formData.get("callbackUrl")?.toString();
if (!email) {
return encodedRedirect("error", "/forgot-password", "Email is required");
}
const { error } = await supabase.auth.resetPasswordForEmail(email, {
redirectTo: `${origin}/auth/callback?redirect_to=/protected/reset-password`,
});
if (error) {
console.error(error.message);
return encodedRedirect(
"error",
"/forgot-password",
"Could not reset password",
);
}
if (callbackUrl) {
return redirect(callbackUrl);
}
return encodedRedirect(
"success",
"/forgot-password",
"Check your email for a link to reset your password.",
);
};
export const resetPasswordAction = async (formData: FormData) => {
const supabase = await createClient();
const password = formData.get("password") as string;
const confirmPassword = formData.get("confirmPassword") as string;
if (!password || !confirmPassword) {
encodedRedirect(
"error",
"/protected/reset-password",
"Password and confirm password are required",
);
}
if (password !== confirmPassword) {
encodedRedirect(
"error",
"/protected/reset-password",
"Passwords do not match",
);
}
const { error } = await supabase.auth.updateUser({
password: password,
});
if (error) {
encodedRedirect(
"error",
"/protected/reset-password",
"Password update failed",
);
}
encodedRedirect("success", "/protected/reset-password", "Password updated");
};
export const signOutAction = async () => {
const supabase = await createClient();
await supabase.auth.signOut();
return redirect("/sign-in");
};
import { createClient } from "@/utils/supabase/server";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
// The `/auth/callback` route is required for the server-side auth flow implemented
// by the SSR package. It exchanges an auth code for the user's session.
// https://supabase.com/docs/guides/auth/server-side/nextjs
const requestUrl = new URL(request.url);
const code = requestUrl.searchParams.get("code");
const origin = requestUrl.origin;
const redirectTo = requestUrl.searchParams.get("redirect_to")?.toString();
if (code) {
const supabase = await createClient();
await supabase.auth.exchangeCodeForSession(code);
}
if (redirectTo) {
return NextResponse.redirect(`${origin}${redirectTo}`);
}
// URL to redirect to after sign up process completes
return NextResponse.redirect(`${origin}/protected`);
}
import { createClient } from "@/lib/supabase/server";
import { type EmailOtpType } from "@supabase/supabase-js";
import { redirect } from "next/navigation";
import { type NextRequest } from "next/server";
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const token_hash = searchParams.get("token_hash");
const type = searchParams.get("type") as EmailOtpType | null;
const next = searchParams.get("next") ?? "/";
if (token_hash && type) {
const supabase = await createClient();
const { error } = await supabase.auth.verifyOtp({
type,
token_hash,
});
if (!error) {
// redirect user to specified redirect URL or root of app
redirect(next);
} else {
// redirect the user to an error page with some instructions
redirect(`/auth/error?error=${error?.message}`);
}
}
// redirect the user to an error page with some instructions
redirect(`/auth/error?error=No token hash or type`);
}
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ error: string }>;
}) {
const params = await searchParams;
return (
<div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
<div className="w-full max-w-sm">
<div className="flex flex-col gap-6">
<Card>
<CardHeader>
<CardTitle className="text-2xl">
Sorry, something went wrong.
</CardTitle>
</CardHeader>
<CardContent>
{params?.error ? (
<p className="text-sm text-muted-foreground">
Code error: {params.error}
</p>
) : (
<p className="text-sm text-muted-foreground">
An unspecified error occurred.
</p>
)}
</CardContent>
</Card>
</div>
</div>
</div>
);
}
import { ForgotPasswordForm } from "@/components/forgot-password-form";
export default function Page() {
return (
<div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
<div className="w-full max-w-sm">
<ForgotPasswordForm />
</div>
</div>
);
}
import { LoginForm } from "@/components/login-form";
export default function Page() {
return (
<div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
<div className="w-full max-w-sm">
<LoginForm />
</div>
</div>
);
}
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
export default function Page() {
return (
<div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
<div className="w-full max-w-sm">
<div className="flex flex-col gap-6">
<Card>
<CardHeader>
<CardTitle className="text-2xl">
Thank you for signing up!
</CardTitle>
<CardDescription>Check your email to confirm</CardDescription>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
You&apos;ve successfully signed up. Please check your email to
confirm your account before signing in.
</p>
</CardContent>
</Card>
</div>
</div>
</div>
);
}
import { SignUpForm } from "@/components/sign-up-form";
export default function Page() {
return (
<div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
<div className="w-full max-w-sm">
<SignUpForm />
</div>
</div>
);
}
import { UpdatePasswordForm } from "@/components/update-password-form";
export default function Page() {
return (
<div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
<div className="w-full max-w-sm">
<UpdatePasswordForm />
</div>
</div>
);
}
...@@ -23,14 +23,13 @@ ...@@ -23,14 +23,13 @@
--border: 0 0% 89.8%; --border: 0 0% 89.8%;
--input: 0 0% 89.8%; --input: 0 0% 89.8%;
--ring: 0 0% 3.9%; --ring: 0 0% 3.9%;
--radius: 0.5rem;
--chart-1: 12 76% 61%; --chart-1: 12 76% 61%;
--chart-2: 173 58% 39%; --chart-2: 173 58% 39%;
--chart-3: 197 37% 24%; --chart-3: 197 37% 24%;
--chart-4: 43 74% 66%; --chart-4: 43 74% 66%;
--chart-5: 27 87% 67%; --chart-5: 27 87% 67%;
--radius: 0.5rem;
} }
.dark { .dark {
--background: 0 0% 3.9%; --background: 0 0% 3.9%;
--foreground: 0 0% 98%; --foreground: 0 0% 98%;
......
import DeployButton from "@/components/deploy-button"; import type { Metadata } from "next";
import { EnvVarWarning } from "@/components/env-var-warning";
import HeaderAuth from "@/components/header-auth";
import { ThemeSwitcher } from "@/components/theme-switcher";
import { hasEnvVars } from "@/utils/supabase/check-env-vars";
import { Geist } from "next/font/google"; import { Geist } from "next/font/google";
import { ThemeProvider } from "next-themes"; import { ThemeProvider } from "next-themes";
import Link from "next/link";
import "./globals.css"; import "./globals.css";
const defaultUrl = process.env.VERCEL_URL const defaultUrl = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}` ? `https://${process.env.VERCEL_URL}`
: "http://localhost:3000"; : "http://localhost:3000";
export const metadata = { export const metadata: Metadata = {
metadataBase: new URL(defaultUrl), metadataBase: new URL(defaultUrl),
title: "Next.js and Supabase Starter Kit", title: "Next.js and Supabase Starter Kit",
description: "The fastest way to build apps with Next.js and Supabase", description: "The fastest way to build apps with Next.js and Supabase",
}; };
const geistSans = Geist({ const geistSans = Geist({
variable: "--font-geist-sans",
display: "swap", display: "swap",
subsets: ["latin"], subsets: ["latin"],
}); });
...@@ -29,47 +25,15 @@ export default function RootLayout({ ...@@ -29,47 +25,15 @@ export default function RootLayout({
children: React.ReactNode; children: React.ReactNode;
}>) { }>) {
return ( return (
<html lang="en" className={geistSans.className} suppressHydrationWarning> <html lang="en" suppressHydrationWarning>
<body className="bg-background text-foreground"> <body className={`${geistSans.className} antialiased`}>
<ThemeProvider <ThemeProvider
attribute="class" attribute="class"
defaultTheme="system" defaultTheme="system"
enableSystem enableSystem
disableTransitionOnChange disableTransitionOnChange
> >
<main className="min-h-screen flex flex-col items-center"> {children}
<div className="flex-1 w-full flex flex-col gap-20 items-center">
<nav className="w-full flex justify-center border-b border-b-foreground/10 h-16">
<div className="w-full max-w-5xl flex justify-between items-center p-3 px-5 text-sm">
<div className="flex gap-5 items-center font-semibold">
<Link href={"/"}>Next.js Supabase Starter</Link>
<div className="flex items-center gap-2">
<DeployButton />
</div>
</div>
{!hasEnvVars ? <EnvVarWarning /> : <HeaderAuth />}
</div>
</nav>
<div className="flex flex-col gap-20 max-w-5xl p-5">
{children}
</div>
<footer className="w-full flex items-center justify-center border-t mx-auto text-center text-xs gap-8 py-16">
<p>
Powered by{" "}
<a
href="https://supabase.com/?utm_source=create-next-app&utm_medium=template&utm_term=nextjs"
target="_blank"
className="font-bold hover:underline"
rel="noreferrer"
>
Supabase
</a>
</p>
<ThemeSwitcher />
</footer>
</div>
</main>
</ThemeProvider> </ThemeProvider>
</body> </body>
</html> </html>
......
import Hero from "@/components/hero"; import { DeployButton } from "@/components/deploy-button";
import ConnectSupabaseSteps from "@/components/tutorial/connect-supabase-steps"; import { EnvVarWarning } from "@/components/env-var-warning";
import SignUpUserSteps from "@/components/tutorial/sign-up-user-steps"; import { AuthButton } from "@/components/auth-button";
import { hasEnvVars } from "@/utils/supabase/check-env-vars"; import { Hero } from "@/components/hero";
import { ThemeSwitcher } from "@/components/theme-switcher";
import { ConnectSupabaseSteps } from "@/components/tutorial/connect-supabase-steps";
import { SignUpUserSteps } from "@/components/tutorial/sign-up-user-steps";
import { hasEnvVars } from "@/lib/utils";
import Link from "next/link";
export default async function Home() { export default function Home() {
return ( return (
<> <main className="min-h-screen flex flex-col items-center">
<Hero /> <div className="flex-1 w-full flex flex-col gap-20 items-center">
<main className="flex-1 flex flex-col gap-6 px-4"> <nav className="w-full flex justify-center border-b border-b-foreground/10 h-16">
<h2 className="font-medium text-xl mb-4">Next steps</h2> <div className="w-full max-w-5xl flex justify-between items-center p-3 px-5 text-sm">
{hasEnvVars ? <SignUpUserSteps /> : <ConnectSupabaseSteps />} <div className="flex gap-5 items-center font-semibold">
</main> <Link href={"/"}>Next.js Supabase Starter</Link>
</> <div className="flex items-center gap-2">
<DeployButton />
</div>
</div>
{!hasEnvVars ? <EnvVarWarning /> : <AuthButton />}
</div>
</nav>
<div className="flex-1 flex flex-col gap-20 max-w-5xl p-5">
<Hero />
<main className="flex-1 flex flex-col gap-6 px-4">
<h2 className="font-medium text-xl mb-4">Next steps</h2>
{hasEnvVars ? <SignUpUserSteps /> : <ConnectSupabaseSteps />}
</main>
</div>
<footer className="w-full flex items-center justify-center border-t mx-auto text-center text-xs gap-8 py-16">
<p>
Powered by{" "}
<a
href="https://supabase.com/?utm_source=create-next-app&utm_medium=template&utm_term=nextjs"
target="_blank"
className="font-bold hover:underline"
rel="noreferrer"
>
Supabase
</a>
</p>
<ThemeSwitcher />
</footer>
</div>
</main>
); );
} }
import { DeployButton } from "@/components/deploy-button";
import { EnvVarWarning } from "@/components/env-var-warning";
import { AuthButton } from "@/components/auth-button";
import { ThemeSwitcher } from "@/components/theme-switcher";
import { hasEnvVars } from "@/lib/utils";
import Link from "next/link";
export default function ProtectedLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<main className="min-h-screen flex flex-col items-center">
<div className="flex-1 w-full flex flex-col gap-20 items-center">
<nav className="w-full flex justify-center border-b border-b-foreground/10 h-16">
<div className="w-full max-w-5xl flex justify-between items-center p-3 px-5 text-sm">
<div className="flex gap-5 items-center font-semibold">
<Link href={"/"}>Next.js Supabase Starter</Link>
<div className="flex items-center gap-2">
<DeployButton />
</div>
</div>
{!hasEnvVars ? <EnvVarWarning /> : <AuthButton />}
</div>
</nav>
<div className="flex-1 flex flex-col gap-20 max-w-5xl p-5">
{children}
</div>
<footer className="w-full flex items-center justify-center border-t mx-auto text-center text-xs gap-8 py-16">
<p>
Powered by{" "}
<a
href="https://supabase.com/?utm_source=create-next-app&utm_medium=template&utm_term=nextjs"
target="_blank"
className="font-bold hover:underline"
rel="noreferrer"
>
Supabase
</a>
</p>
<ThemeSwitcher />
</footer>
</div>
</main>
);
}
import FetchDataSteps from "@/components/tutorial/fetch-data-steps";
import { createClient } from "@/utils/supabase/server";
import { InfoIcon } from "lucide-react";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { InfoIcon } from "lucide-react";
import { FetchDataSteps } from "@/components/tutorial/fetch-data-steps";
export default async function ProtectedPage() { export default async function ProtectedPage() {
const supabase = await createClient(); const supabase = await createClient();
const { const { data, error } = await supabase.auth.getUser();
data: { user }, if (error || !data?.user) {
} = await supabase.auth.getUser(); redirect("/auth/login");
if (!user) {
return redirect("/sign-in");
} }
return ( return (
...@@ -26,7 +24,7 @@ export default async function ProtectedPage() { ...@@ -26,7 +24,7 @@ export default async function ProtectedPage() {
<div className="flex flex-col gap-2 items-start"> <div className="flex flex-col gap-2 items-start">
<h2 className="font-bold text-2xl mb-4">Your user details</h2> <h2 className="font-bold text-2xl mb-4">Your user details</h2>
<pre className="text-xs font-mono p-3 rounded border max-h-32 overflow-auto"> <pre className="text-xs font-mono p-3 rounded border max-h-32 overflow-auto">
{JSON.stringify(user, null, 2)} {JSON.stringify(data.user, null, 2)}
</pre> </pre>
</div> </div>
<div> <div>
......
import { resetPasswordAction } from "@/app/actions";
import { FormMessage, Message } from "@/components/form-message";
import { SubmitButton } from "@/components/submit-button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
export default async function ResetPassword(props: {
searchParams: Promise<Message>;
}) {
const searchParams = await props.searchParams;
return (
<form className="flex flex-col w-full max-w-md p-4 gap-2 [&>input]:mb-4">
<h1 className="text-2xl font-medium">Reset password</h1>
<p className="text-sm text-foreground/60">
Please enter your new password below.
</p>
<Label htmlFor="password">New password</Label>
<Input
type="password"
name="password"
placeholder="New password"
required
/>
<Label htmlFor="confirmPassword">Confirm password</Label>
<Input
type="password"
name="confirmPassword"
placeholder="Confirm password"
required
/>
<SubmitButton formAction={resetPasswordAction}>
Reset password
</SubmitButton>
<FormMessage message={searchParams} />
</form>
);
}
{ {
"$schema": "https://ui.shadcn.com/schema.json", "$schema": "https://ui.shadcn.com/schema.json",
"style": "default", "style": "new-york",
"rsc": true, "rsc": true,
"tsx": true, "tsx": true,
"tailwind": { "tailwind": {
"config": "tailwind.config.ts", "config": "",
"css": "app/globals.css", "css": "app/globals.css",
"baseColor": "neutral", "baseColor": "neutral",
"cssVariables": true, "cssVariables": true,
...@@ -12,6 +12,10 @@ ...@@ -12,6 +12,10 @@
}, },
"aliases": { "aliases": {
"components": "@/components", "components": "@/components",
"utils": "@/lib/utils" "utils": "@/lib/utils",
} "ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
} }
import Link from "next/link";
import { Button } from "./ui/button";
import { createClient } from "@/lib/supabase/server";
import { LogoutButton } from "./logout-button";
export async function AuthButton() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
return user ? (
<div className="flex items-center gap-4">
Hey, {user.email}!
<LogoutButton />
</div>
) : (
<div className="flex gap-2">
<Button asChild size="sm" variant={"outline"}>
<Link href="/auth/login">Sign in</Link>
</Button>
<Button asChild size="sm" variant={"default"}>
<Link href="/auth/sign-up">Sign up</Link>
</Button>
</div>
);
}
import Link from "next/link"; import Link from "next/link";
import { Button } from "./ui/button"; import { Button } from "./ui/button";
export default function DeployButton() { export function DeployButton() {
return ( return (
<> <>
<Link <Link
href="https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-supabase&project-name=nextjs-with-supabase&repository-name=nextjs-with-supabase&demo-title=nextjs-with-supabase&demo-description=This+starter+configures+Supabase+Auth+to+use+cookies%2C+making+the+user%27s+session+available+throughout+the+entire+Next.js+app+-+Client+Components%2C+Server+Components%2C+Route+Handlers%2C+Server+Actions+and+Middleware.&demo-url=https%3A%2F%2Fdemo-nextjs-with-supabase.vercel.app%2F&external-id=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-supabase&demo-image=https%3A%2F%2Fdemo-nextjs-with-supabase.vercel.app%2Fopengraph-image.png" href="https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-supabase&project-name=nextjs-with-supabase&repository-name=nextjs-with-supabase&demo-title=nextjs-with-supabase&demo-description=This+starter+configures+Supabase+Auth+to+use+cookies%2C+making+the+user%27s+session+available+throughout+the+entire+Next.js+app+-+Client+Components%2C+Server+Components%2C+Route+Handlers%2C+Server+Actions+and+Middleware.&demo-url=https%3A%2F%2Fdemo-nextjs-with-supabase.vercel.app%2F&external-id=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-supabase&demo-image=https%3A%2F%2Fdemo-nextjs-with-supabase.vercel.app%2Fopengraph-image.png"
target="_blank" target="_blank"
> >
<Button className="flex items-center gap-2" size={"sm"}> <Button className="flex items-center gap-2" size="sm">
<svg <svg
className="h-3 w-3" className="h-3 w-3"
viewBox="0 0 76 65" viewBox="0 0 76 65"
......
import Link from "next/link";
import { Badge } from "./ui/badge"; import { Badge } from "./ui/badge";
import { Button } from "./ui/button"; import { Button } from "./ui/button";
...@@ -9,23 +8,11 @@ export function EnvVarWarning() { ...@@ -9,23 +8,11 @@ export function EnvVarWarning() {
Supabase environment variables required Supabase environment variables required
</Badge> </Badge>
<div className="flex gap-2"> <div className="flex gap-2">
<Button <Button size="sm" variant={"outline"} disabled>
asChild Sign in
size="sm"
variant={"outline"}
disabled
className="opacity-75 cursor-none pointer-events-none"
>
<Link href="/sign-in">Sign in</Link>
</Button> </Button>
<Button <Button size="sm" variant={"default"} disabled>
asChild Sign up
size="sm"
variant={"default"}
disabled
className="opacity-75 cursor-none pointer-events-none"
>
<Link href="/sign-up">Sign up</Link>
</Button> </Button>
</div> </div>
</div> </div>
......
"use client";
import { cn } from "@/lib/utils";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import Link from "next/link";
import { useState } from "react";
export function ForgotPasswordForm({
className,
...props
}: React.ComponentPropsWithoutRef<"div">) {
const [email, setEmail] = useState("");
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const handleForgotPassword = async (e: React.FormEvent) => {
e.preventDefault();
const supabase = createClient();
setIsLoading(true);
setError(null);
try {
// The url which will be included in the email. This URL needs to be configured in your redirect URLs in the Supabase dashboard at https://supabase.com/dashboard/project/_/auth/url-configuration
const { error } = await supabase.auth.resetPasswordForEmail(email, {
redirectTo: `${window.location.origin}/auth/update-password`,
});
if (error) throw error;
setSuccess(true);
} catch (error: unknown) {
setError(error instanceof Error ? error.message : "An error occurred");
} finally {
setIsLoading(false);
}
};
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
{success ? (
<Card>
<CardHeader>
<CardTitle className="text-2xl">Check Your Email</CardTitle>
<CardDescription>Password reset instructions sent</CardDescription>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
If you registered using your email and password, you will receive
a password reset email.
</p>
</CardContent>
</Card>
) : (
<Card>
<CardHeader>
<CardTitle className="text-2xl">Reset Your Password</CardTitle>
<CardDescription>
Type in your email and we&apos;ll send you a link to reset your
password
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleForgotPassword}>
<div className="flex flex-col gap-6">
<div className="grid gap-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="m@example.com"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
{error && <p className="text-sm text-red-500">{error}</p>}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? "Sending..." : "Send reset email"}
</Button>
</div>
<div className="mt-4 text-center text-sm">
Already have an account?{" "}
<Link
href="/auth/login"
className="underline underline-offset-4"
>
Login
</Link>
</div>
</form>
</CardContent>
</Card>
)}
</div>
);
}
export type Message =
| { success: string }
| { error: string }
| { message: string };
export function FormMessage({ message }: { message: Message }) {
return (
<div className="flex flex-col gap-2 w-full max-w-md text-sm">
{"success" in message && (
<div className="text-foreground border-l-2 border-foreground px-4">
{message.success}
</div>
)}
{"error" in message && (
<div className="text-destructive-foreground border-l-2 border-destructive-foreground px-4">
{message.error}
</div>
)}
{"message" in message && (
<div className="text-foreground border-l-2 px-4">{message.message}</div>
)}
</div>
);
}
import { signOutAction } from "@/app/actions";
import { hasEnvVars } from "@/utils/supabase/check-env-vars";
import Link from "next/link";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { createClient } from "@/utils/supabase/server";
export default async function AuthButton() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!hasEnvVars) {
return (
<>
<div className="flex gap-4 items-center">
<div>
<Badge
variant={"default"}
className="font-normal pointer-events-none"
>
Please update .env.local file with anon key and url
</Badge>
</div>
<div className="flex gap-2">
<Button
asChild
size="sm"
variant={"outline"}
disabled
className="opacity-75 cursor-none pointer-events-none"
>
<Link href="/sign-in">Sign in</Link>
</Button>
<Button
asChild
size="sm"
variant={"default"}
disabled
className="opacity-75 cursor-none pointer-events-none"
>
<Link href="/sign-up">Sign up</Link>
</Button>
</div>
</div>
</>
);
}
return user ? (
<div className="flex items-center gap-4">
Hey, {user.email}!
<form action={signOutAction}>
<Button type="submit" variant={"outline"}>
Sign out
</Button>
</form>
</div>
) : (
<div className="flex gap-2">
<Button asChild size="sm" variant={"outline"}>
<Link href="/sign-in">Sign in</Link>
</Button>
<Button asChild size="sm" variant={"default"}>
<Link href="/sign-up">Sign up</Link>
</Button>
</div>
);
}
import NextLogo from "./next-logo"; import { NextLogo } from "./next-logo";
import SupabaseLogo from "./supabase-logo"; import { SupabaseLogo } from "./supabase-logo";
export default function Header() { export function Hero() {
return ( return (
<div className="flex flex-col gap-16 items-center"> <div className="flex flex-col gap-16 items-center">
<div className="flex gap-8 justify-center items-center"> <div className="flex gap-8 justify-center items-center">
......
"use client";
import { cn } from "@/lib/utils";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
export function LoginForm({
className,
...props
}: React.ComponentPropsWithoutRef<"div">) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
const supabase = createClient();
setIsLoading(true);
setError(null);
try {
const { error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) throw error;
// Update this route to redirect to an authenticated route. The user already has an active session.
router.push("/protected");
} catch (error: unknown) {
setError(error instanceof Error ? error.message : "An error occurred");
} finally {
setIsLoading(false);
}
};
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card>
<CardHeader>
<CardTitle className="text-2xl">Login</CardTitle>
<CardDescription>
Enter your email below to login to your account
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleLogin}>
<div className="flex flex-col gap-6">
<div className="grid gap-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="m@example.com"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="grid gap-2">
<div className="flex items-center">
<Label htmlFor="password">Password</Label>
<Link
href="/auth/forgot-password"
className="ml-auto inline-block text-sm underline-offset-4 hover:underline"
>
Forgot your password?
</Link>
</div>
<Input
id="password"
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
{error && <p className="text-sm text-red-500">{error}</p>}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? "Logging in..." : "Login"}
</Button>
</div>
<div className="mt-4 text-center text-sm">
Don&apos;t have an account?{" "}
<Link
href="/auth/sign-up"
className="underline underline-offset-4"
>
Sign up
</Link>
</div>
</form>
</CardContent>
</Card>
</div>
);
}
"use client";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { useRouter } from "next/navigation";
export function LogoutButton() {
const router = useRouter();
const logout = async () => {
const supabase = createClient();
await supabase.auth.signOut();
router.push("/auth/login");
};
return <Button onClick={logout}>Logout</Button>;
}
export default function NextLogo() { export function NextLogo() {
return ( return (
<svg <svg
aria-label="Next.js logotype" aria-label="Next.js logotype"
......
"use client";
import { cn } from "@/lib/utils";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
export function SignUpForm({
className,
...props
}: React.ComponentPropsWithoutRef<"div">) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [repeatPassword, setRepeatPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const handleSignUp = async (e: React.FormEvent) => {
e.preventDefault();
const supabase = createClient();
setIsLoading(true);
setError(null);
if (password !== repeatPassword) {
setError("Passwords do not match");
setIsLoading(false);
return;
}
try {
const { error } = await supabase.auth.signUp({
email,
password,
options: {
emailRedirectTo: `${window.location.origin}/protected`,
},
});
if (error) throw error;
router.push("/auth/sign-up-success");
} catch (error: unknown) {
setError(error instanceof Error ? error.message : "An error occurred");
} finally {
setIsLoading(false);
}
};
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card>
<CardHeader>
<CardTitle className="text-2xl">Sign up</CardTitle>
<CardDescription>Create a new account</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSignUp}>
<div className="flex flex-col gap-6">
<div className="grid gap-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="m@example.com"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="grid gap-2">
<div className="flex items-center">
<Label htmlFor="password">Password</Label>
</div>
<Input
id="password"
type="password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="grid gap-2">
<div className="flex items-center">
<Label htmlFor="repeat-password">Repeat Password</Label>
</div>
<Input
id="repeat-password"
type="password"
required
value={repeatPassword}
onChange={(e) => setRepeatPassword(e.target.value)}
/>
</div>
{error && <p className="text-sm text-red-500">{error}</p>}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? "Creating an account..." : "Sign up"}
</Button>
</div>
<div className="mt-4 text-center text-sm">
Already have an account?{" "}
<Link href="/auth/login" className="underline underline-offset-4">
Login
</Link>
</div>
</form>
</CardContent>
</Card>
</div>
);
}
"use client";
import { Button } from "@/components/ui/button";
import { type ComponentProps } from "react";
import { useFormStatus } from "react-dom";
type Props = ComponentProps<typeof Button> & {
pendingText?: string;
};
export function SubmitButton({
children,
pendingText = "Submitting...",
...props
}: Props) {
const { pending } = useFormStatus();
return (
<Button type="submit" aria-disabled={pending} {...props}>
{pending ? pendingText : children}
</Button>
);
}
export default function SupabaseLogo() { export function SupabaseLogo() {
return ( return (
<svg <svg
aria-label="Supabase logo" aria-label="Supabase logo"
......
import { TutorialStep } from "./tutorial-step"; import { TutorialStep } from "./tutorial-step";
export default function ConnectSupabaseSteps() { export function ConnectSupabaseSteps() {
return ( return (
<ol className="flex flex-col gap-6"> <ol className="flex flex-col gap-6">
<TutorialStep title="Create Supabase project"> <TutorialStep title="Create Supabase project">
...@@ -35,7 +35,7 @@ export default function ConnectSupabaseSteps() { ...@@ -35,7 +35,7 @@ export default function ConnectSupabaseSteps() {
className="font-bold hover:underline text-foreground/80" className="font-bold hover:underline text-foreground/80"
rel="noreferrer" rel="noreferrer"
> >
your Supabase project's API Settings your Supabase project&apos;s API Settings
</a> </a>
. .
</p> </p>
......
...@@ -44,7 +44,7 @@ export default function Page() { ...@@ -44,7 +44,7 @@ export default function Page() {
} }
`.trim(); `.trim();
export default function FetchDataSteps() { export function FetchDataSteps() {
return ( return (
<ol className="flex flex-col gap-6"> <ol className="flex flex-col gap-6">
<TutorialStep title="Create some tables and insert some data"> <TutorialStep title="Create some tables and insert some data">
...@@ -59,7 +59,7 @@ export default function FetchDataSteps() { ...@@ -59,7 +59,7 @@ export default function FetchDataSteps() {
Table Editor Table Editor
</a>{" "} </a>{" "}
for your Supabase project to create a table and insert some example for your Supabase project to create a table and insert some example
data. If you're stuck for creativity, you can copy and paste the data. If you&apos;re stuck for creativity, you can copy and paste the
following into the{" "} following into the{" "}
<a <a
href="https://supabase.com/dashboard/project/_/sql/new" href="https://supabase.com/dashboard/project/_/sql/new"
...@@ -88,8 +88,27 @@ export default function FetchDataSteps() { ...@@ -88,8 +88,27 @@ export default function FetchDataSteps() {
<CodeBlock code={client} /> <CodeBlock code={client} />
</TutorialStep> </TutorialStep>
<TutorialStep title="Explore the Supabase UI Library">
<p>
Head over to the{" "}
<a
href="https://supabase.com/ui"
className="font-bold hover:underline text-foreground/80"
>
Supabase UI library
</a>{" "}
and try installing some blocks. For example, you can install a
Realtime Chat block by running:
</p>
<CodeBlock
code={
"npx shadcn@latest add https://supabase.com/ui/r/realtime-chat-nextjs.json"
}
/>
</TutorialStep>
<TutorialStep title="Build in a weekend and scale to millions!"> <TutorialStep title="Build in a weekend and scale to millions!">
<p>You're ready to launch your product to the world! 🚀</p> <p>You&apos;re ready to launch your product to the world! 🚀</p>
</TutorialStep> </TutorialStep>
</ol> </ol>
); );
......
...@@ -2,7 +2,7 @@ import Link from "next/link"; ...@@ -2,7 +2,7 @@ import Link from "next/link";
import { TutorialStep } from "./tutorial-step"; import { TutorialStep } from "./tutorial-step";
import { ArrowUpRight } from "lucide-react"; import { ArrowUpRight } from "lucide-react";
export default function SignUpUserSteps() { export function SignUpUserSteps() {
return ( return (
<ol className="flex flex-col gap-6"> <ol className="flex flex-col gap-6">
{process.env.VERCEL_ENV === "preview" || {process.env.VERCEL_ENV === "preview" ||
...@@ -12,7 +12,7 @@ export default function SignUpUserSteps() { ...@@ -12,7 +12,7 @@ export default function SignUpUserSteps() {
<p className="mt-4"> <p className="mt-4">
This particular deployment is This particular deployment is
<span className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs font-medium text-secondary-foreground border"> <span className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs font-medium text-secondary-foreground border">
"{process.env.VERCEL_ENV}" &quot;{process.env.VERCEL_ENV}&quot;
</span>{" "} </span>{" "}
on on
<span className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs font-medium text-secondary-foreground border"> <span className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs font-medium text-secondary-foreground border">
...@@ -48,7 +48,10 @@ export default function SignUpUserSteps() { ...@@ -48,7 +48,10 @@ export default function SignUpUserSteps() {
<li> <li>
-{" "} -{" "}
<span className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs font-medium text-secondary-foreground border"> <span className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs font-medium text-secondary-foreground border">
{`https://${process.env.VERCEL_PROJECT_PRODUCTION_URL?.replace(".vercel.app", "")}-*-[vercel-team-url].vercel.app/**`} {`https://${process.env.VERCEL_PROJECT_PRODUCTION_URL?.replace(
".vercel.app",
"",
)}-*-[vercel-team-url].vercel.app/**`}
</span>{" "} </span>{" "}
(Vercel Team URL can be found in{" "} (Vercel Team URL can be found in{" "}
<Link <Link
...@@ -74,13 +77,13 @@ export default function SignUpUserSteps() { ...@@ -74,13 +77,13 @@ export default function SignUpUserSteps() {
<p> <p>
Head over to the{" "} Head over to the{" "}
<Link <Link
href="/sign-up" href="auth/sign-up"
className="font-bold hover:underline text-foreground/80" className="font-bold hover:underline text-foreground/80"
> >
Sign up Sign up
</Link>{" "} </Link>{" "}
page and sign up your first user. It's okay if this is just you for page and sign up your first user. It&apos;s okay if this is just you
now. Your awesome idea will have plenty of users later! for now. Your awesome idea will have plenty of users later!
</p> </p>
</TutorialStep> </TutorialStep>
</ol> </ol>
......
export function TypographyInlineCode() {
return (
<code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">
@radix-ui/react-alert-dialog
</code>
);
}
...@@ -4,16 +4,16 @@ import { cva, type VariantProps } from "class-variance-authority"; ...@@ -4,16 +4,16 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
const badgeVariants = cva( const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{ {
variants: { variants: {
variant: { variant: {
default: default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80", "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
secondary: secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive: destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80", "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
outline: "text-foreground", outline: "text-foreground",
}, },
}, },
......
...@@ -5,25 +5,26 @@ import { cva, type VariantProps } from "class-variance-authority"; ...@@ -5,25 +5,26 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
const buttonVariants = cva( const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50", "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{ {
variants: { variants: {
variant: { variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90", default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive: destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90", "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline: outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground", "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary: secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80", "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground", ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline", link: "text-primary underline-offset-4 hover:underline",
}, },
size: { size: {
default: "h-10 px-4 py-2", default: "h-9 px-4 py-2",
sm: "h-9 rounded-md px-3", sm: "h-8 rounded-md px-3 text-xs",
lg: "h-11 rounded-md px-8", lg: "h-10 rounded-md px-8",
icon: "h-10 w-10", icon: "h-9 w-9",
}, },
}, },
defaultVariants: { defaultVariants: {
......
import * as React from "react";
import { cn } from "@/lib/utils";
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className,
)}
{...props}
/>
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
));
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
));
CardFooter.displayName = "CardFooter";
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardDescription,
CardContent,
};
...@@ -13,7 +13,7 @@ const Checkbox = React.forwardRef< ...@@ -13,7 +13,7 @@ const Checkbox = React.forwardRef<
<CheckboxPrimitive.Root <CheckboxPrimitive.Root
ref={ref} ref={ref}
className={cn( className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground", "peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className, className,
)} )}
{...props} {...props}
......
...@@ -27,14 +27,14 @@ const DropdownMenuSubTrigger = React.forwardRef< ...@@ -27,14 +27,14 @@ const DropdownMenuSubTrigger = React.forwardRef<
<DropdownMenuPrimitive.SubTrigger <DropdownMenuPrimitive.SubTrigger
ref={ref} ref={ref}
className={cn( className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent", "flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
inset && "pl-8", inset && "pl-8",
className, className,
)} )}
{...props} {...props}
> >
{children} {children}
<ChevronRight className="ml-auto h-4 w-4" /> <ChevronRight className="ml-auto" />
</DropdownMenuPrimitive.SubTrigger> </DropdownMenuPrimitive.SubTrigger>
)); ));
DropdownMenuSubTrigger.displayName = DropdownMenuSubTrigger.displayName =
...@@ -47,7 +47,7 @@ const DropdownMenuSubContent = React.forwardRef< ...@@ -47,7 +47,7 @@ const DropdownMenuSubContent = React.forwardRef<
<DropdownMenuPrimitive.SubContent <DropdownMenuPrimitive.SubContent
ref={ref} ref={ref}
className={cn( className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",
className, className,
)} )}
{...props} {...props}
...@@ -65,7 +65,8 @@ const DropdownMenuContent = React.forwardRef< ...@@ -65,7 +65,8 @@ const DropdownMenuContent = React.forwardRef<
ref={ref} ref={ref}
sideOffset={sideOffset} sideOffset={sideOffset}
className={cn( className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", "z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",
className, className,
)} )}
{...props} {...props}
...@@ -83,7 +84,7 @@ const DropdownMenuItem = React.forwardRef< ...@@ -83,7 +84,7 @@ const DropdownMenuItem = React.forwardRef<
<DropdownMenuPrimitive.Item <DropdownMenuPrimitive.Item
ref={ref} ref={ref}
className={cn( className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", "relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
inset && "pl-8", inset && "pl-8",
className, className,
)} )}
......
...@@ -2,16 +2,13 @@ import * as React from "react"; ...@@ -2,16 +2,13 @@ import * as React from "react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
export interface InputProps const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => { ({ className, type, ...props }, ref) => {
return ( return (
<input <input
type={type} type={type}
className={cn( className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50", "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className, className,
)} )}
ref={ref} ref={ref}
......
"use client";
import { cn } from "@/lib/utils";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useRouter } from "next/navigation";
import { useState } from "react";
export function UpdatePasswordForm({
className,
...props
}: React.ComponentPropsWithoutRef<"div">) {
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const handleForgotPassword = async (e: React.FormEvent) => {
e.preventDefault();
const supabase = createClient();
setIsLoading(true);
setError(null);
try {
const { error } = await supabase.auth.updateUser({ password });
if (error) throw error;
// Update this route to redirect to an authenticated route. The user already has an active session.
router.push("/protected");
} catch (error: unknown) {
setError(error instanceof Error ? error.message : "An error occurred");
} finally {
setIsLoading(false);
}
};
return (
<div className={cn("flex flex-col gap-6", className)} {...props}>
<Card>
<CardHeader>
<CardTitle className="text-2xl">Reset Your Password</CardTitle>
<CardDescription>
Please enter your new password below.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleForgotPassword}>
<div className="flex flex-col gap-6">
<div className="grid gap-2">
<Label htmlFor="password">New password</Label>
<Input
id="password"
type="password"
placeholder="New password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
{error && <p className="text-sm text-red-500">{error}</p>}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? "Saving..." : "Save new password"}
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
);
}
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
];
export default eslintConfig;
import { createBrowserClient } from "@supabase/ssr"; import { createBrowserClient } from "@supabase/ssr";
export const createClient = () => export function createClient() {
createBrowserClient( return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
); );
}
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
import { hasEnvVars } from "../utils";
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
request,
});
// If the env vars are not set, skip middleware check. You can remove this once you setup the project.
if (!hasEnvVars) {
return supabaseResponse;
}
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) =>
request.cookies.set(name, value),
);
supabaseResponse = NextResponse.next({
request,
});
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options),
);
},
},
},
);
// Do not run code between createServerClient and
// supabase.auth.getUser(). A simple mistake could make it very hard to debug
// issues with users being randomly logged out.
// IMPORTANT: DO NOT REMOVE auth.getUser()
const {
data: { user },
} = await supabase.auth.getUser();
if (
request.nextUrl.pathname !== "/" &&
!user &&
!request.nextUrl.pathname.startsWith("/login") &&
!request.nextUrl.pathname.startsWith("/auth")
) {
// no user, potentially respond by redirecting the user to the login page
const url = request.nextUrl.clone();
url.pathname = "/auth/login";
return NextResponse.redirect(url);
}
// IMPORTANT: You *must* return the supabaseResponse object as it is.
// If you're creating a new response object with NextResponse.next() make sure to:
// 1. Pass the request in it, like so:
// const myNewResponse = NextResponse.next({ request })
// 2. Copy over the cookies, like so:
// myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())
// 3. Change the myNewResponse object to fit your needs, but avoid changing
// the cookies!
// 4. Finally:
// return myNewResponse
// If this is not done, you may be causing the browser and server to go out
// of sync and terminate the user's session prematurely!
return supabaseResponse;
}
import { createServerClient } from "@supabase/ssr"; import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
export const createClient = async () => { export async function createClient() {
const cookieStore = await cookies(); const cookieStore = await cookies();
return createServerClient( return createServerClient(
...@@ -14,11 +14,11 @@ export const createClient = async () => { ...@@ -14,11 +14,11 @@ export const createClient = async () => {
}, },
setAll(cookiesToSet) { setAll(cookiesToSet) {
try { try {
cookiesToSet.forEach(({ name, value, options }) => { cookiesToSet.forEach(({ name, value, options }) =>
cookieStore.set(name, value, options); cookieStore.set(name, value, options),
}); );
} catch (error) { } catch {
// The `set` method was called from a Server Component. // The `setAll` method was called from a Server Component.
// This can be ignored if you have middleware refreshing // This can be ignored if you have middleware refreshing
// user sessions. // user sessions.
} }
...@@ -26,4 +26,4 @@ export const createClient = async () => { ...@@ -26,4 +26,4 @@ export const createClient = async () => {
}, },
}, },
); );
}; }
...@@ -4,3 +4,8 @@ import { twMerge } from "tailwind-merge"; ...@@ -4,3 +4,8 @@ import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)); return twMerge(clsx(inputs));
} }
// This check can be removed, it is just for tutorial purposes
export const hasEnvVars =
process.env.NEXT_PUBLIC_SUPABASE_URL &&
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
import { updateSession } from "@/lib/supabase/middleware";
import { type NextRequest } from "next/server"; import { type NextRequest } from "next/server";
import { updateSession } from "@/utils/supabase/middleware";
export async function middleware(request: NextRequest) { export async function middleware(request: NextRequest) {
return await updateSession(request); return await updateSession(request);
......
{ {
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev --turbopack",
"build": "next build", "build": "next build",
"start": "next start" "start": "next start",
"lint": "next lint"
}, },
"dependencies": { "dependencies": {
"@radix-ui/react-checkbox": "^1.1.1", "@radix-ui/react-checkbox": "^1.3.1",
"@radix-ui/react-dropdown-menu": "^2.1.1", "@radix-ui/react-dropdown-menu": "^2.1.14",
"@radix-ui/react-label": "^2.1.0", "@radix-ui/react-label": "^2.1.6",
"@radix-ui/react-slot": "^1.1.0", "@radix-ui/react-slot": "^1.2.2",
"@supabase/ssr": "latest", "@supabase/ssr": "latest",
"@supabase/supabase-js": "latest", "@supabase/supabase-js": "latest",
"autoprefixer": "10.4.20", "class-variance-authority": "^0.7.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"lucide-react": "^0.468.0", "lucide-react": "^0.511.0",
"next": "latest", "next": "latest",
"next-themes": "^0.4.3", "next-themes": "^0.4.6",
"prettier": "^3.3.3", "react": "^19.0.0",
"react": "19.0.0", "react-dom": "^19.0.0",
"react-dom": "19.0.0" "tailwind-merge": "^3.3.0"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "22.10.2", "@eslint/eslintrc": "^3",
"@types/react": "^19.0.2", "@types/node": "^20",
"@types/react-dom": "19.0.2", "@types/react": "^19",
"postcss": "8.4.49", "@types/react-dom": "^19",
"tailwind-merge": "^2.5.2", "autoprefixer": "^10.4.20",
"tailwindcss": "3.4.17", "eslint": "^9",
"eslint-config-next": "15.3.1",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"typescript": "5.7.2" "typescript": "^5"
} }
} }
module.exports = { /** @type {import('postcss-load-config').Config} */
const config = {
plugins: { plugins: {
tailwindcss: {}, tailwindcss: {},
autoprefixer: {}, autoprefixer: {},
}, },
}; };
export default config;
import type { Config } from "tailwindcss"; import type { Config } from "tailwindcss";
const config = { export default {
darkMode: ["class"], darkMode: ["class"],
content: [ content: [
"./pages/**/*.{ts,tsx}", "./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{ts,tsx}", "./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{ts,tsx}", "./app/**/*.{js,ts,jsx,tsx,mdx}",
"./src/**/*.{ts,tsx}", "./src/**/*.{js,ts,jsx,tsx,mdx}",
], ],
prefix: "",
theme: { theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
extend: { extend: {
colors: { colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))", background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))", foreground: "hsl(var(--foreground))",
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
primary: { primary: {
DEFAULT: "hsl(var(--primary))", DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))", foreground: "hsl(var(--primary-foreground))",
...@@ -32,10 +29,6 @@ const config = { ...@@ -32,10 +29,6 @@ const config = {
DEFAULT: "hsl(var(--secondary))", DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))", foreground: "hsl(var(--secondary-foreground))",
}, },
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: { muted: {
DEFAULT: "hsl(var(--muted))", DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))", foreground: "hsl(var(--muted-foreground))",
...@@ -44,13 +37,19 @@ const config = { ...@@ -44,13 +37,19 @@ const config = {
DEFAULT: "hsl(var(--accent))", DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))", foreground: "hsl(var(--accent-foreground))",
}, },
popover: { destructive: {
DEFAULT: "hsl(var(--popover))", DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--popover-foreground))", foreground: "hsl(var(--destructive-foreground))",
}, },
card: { border: "hsl(var(--border))",
DEFAULT: "hsl(var(--card))", input: "hsl(var(--input))",
foreground: "hsl(var(--card-foreground))", ring: "hsl(var(--ring))",
chart: {
"1": "hsl(var(--chart-1))",
"2": "hsl(var(--chart-2))",
"3": "hsl(var(--chart-3))",
"4": "hsl(var(--chart-4))",
"5": "hsl(var(--chart-5))",
}, },
}, },
borderRadius: { borderRadius: {
...@@ -58,23 +57,7 @@ const config = { ...@@ -58,23 +57,7 @@ const config = {
md: "calc(var(--radius) - 2px)", md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)", sm: "calc(var(--radius) - 4px)",
}, },
keyframes: {
"accordion-down": {
from: { height: "0" },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: "0" },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
}, },
}, },
plugins: [require("tailwindcss-animate")], plugins: [require("tailwindcss-animate")],
} satisfies Config; } satisfies Config;
export default config;
{ {
"compilerOptions": { "compilerOptions": {
"target": "es5", "target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"], "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
"noEmit": true, "noEmit": true,
"esModuleInterop": true, "esModuleInterop": true,
"module": "esnext", "module": "esnext",
"moduleResolution": "node", "moduleResolution": "bundler",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve", "jsx": "preserve",
......
// This check can be removed
// it is just for tutorial purposes
export const hasEnvVars =
process.env.NEXT_PUBLIC_SUPABASE_URL &&
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
import { createServerClient } from "@supabase/ssr";
import { type NextRequest, NextResponse } from "next/server";
export const updateSession = async (request: NextRequest) => {
// This `try/catch` block is only here for the interactive tutorial.
// Feel free to remove once you have Supabase connected.
try {
// Create an unmodified response
let response = NextResponse.next({
request: {
headers: request.headers,
},
});
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(cookiesToSet) {
cookiesToSet.forEach(({ name, value }) =>
request.cookies.set(name, value),
);
response = NextResponse.next({
request,
});
cookiesToSet.forEach(({ name, value, options }) =>
response.cookies.set(name, value, options),
);
},
},
},
);
// This will refresh session if expired - required for Server Components
// https://supabase.com/docs/guides/auth/server-side/nextjs
const user = await supabase.auth.getUser();
// protected routes
if (request.nextUrl.pathname.startsWith("/protected") && user.error) {
return NextResponse.redirect(new URL("/sign-in", request.url));
}
if (request.nextUrl.pathname === "/" && !user.error) {
return NextResponse.redirect(new URL("/protected", request.url));
}
return response;
} catch (e) {
// If you are here, a Supabase client could not be created!
// This is likely because you have not set up environment variables.
// Check out http://localhost:3000 for Next Steps.
return NextResponse.next({
request: {
headers: request.headers,
},
});
}
};
import { redirect } from "next/navigation";
/**
* Redirects to a specified path with an encoded message as a query parameter.
* @param {('error' | 'success')} type - The type of message, either 'error' or 'success'.
* @param {string} path - The path to redirect to.
* @param {string} message - The message to be encoded and added as a query parameter.
* @returns {never} This function doesn't return as it triggers a redirect.
*/
export function encodedRedirect(
type: "error" | "success",
path: string,
message: string,
) {
return redirect(`${path}?${type}=${encodeURIComponent(message)}`);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment