Skip to content

Create professional demos and 3D mockups in seconds, directly in your browser

feat: enhance locale handling and metadata generation across various components

CristianOlivera19d3bd7939678
diff --git a/app/[locale]/(auth)/login/page.tsx b/app/[locale]/(auth)/login/page.tsx
index 54ad5b1..6698618 100644
--- a/app/[locale]/(auth)/login/page.tsx
+++ b/app/[locale]/(auth)/login/page.tsx
@@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";
import { Icon } from "@iconify/react";
import Image from "next/image";
import { Link } from "@/navigation";
-import { useTranslations } from "next-intl";
+import { useLocale, useTranslations } from "next-intl";
type OAuthProvider = "google" | "github" | "twitch";
@@ -40,8 +40,24 @@ const providers: ProviderConfig[] = [
},
];
+function buildOAuthCallbackUrl(locale: string, redirectedFrom: string | null) {
+ const url = new URL(`/${locale}/auth/callback`, window.location.origin);
+
+ if (
+ redirectedFrom &&
+ redirectedFrom.startsWith("/") &&
+ !redirectedFrom.startsWith("//") &&
+ !redirectedFrom.includes("://")
+ ) {
+ url.searchParams.set("next", redirectedFrom);
+ }
+
+ return url.toString();
+}
+
export default function Login() {
const t = useTranslations('login');
+ const locale = useLocale();
const [loading, setLoading] = useState<OAuthProvider | null>(null);
const [error, setError] = useState<string | null>(null);
const supabase = createClient();
@@ -51,7 +67,10 @@ export default function Login() {
setLoading(provider);
setError(null);
- const redirectUrl = `${window.location.origin}/auth/callback`;
+ const redirectedFrom = new URLSearchParams(window.location.search).get(
+ "redirectedFrom",
+ );
+ const redirectUrl = buildOAuthCallbackUrl(locale, redirectedFrom);
const { error: signInError } = await supabase.auth.signInWithOAuth({
provider,
diff --git a/app/[locale]/(home)/donate/page.tsx b/app/[locale]/(home)/donate/page.tsx
index db938ed..e485558 100644
--- a/app/[locale]/(home)/donate/page.tsx
+++ b/app/[locale]/(home)/donate/page.tsx
@@ -2,7 +2,7 @@ import { headers } from "next/headers";
import { getTranslations } from "next-intl/server";
import type { Metadata } from "next";
import DonateClient from "./DonateClient";
-import { getRouteAlternates, SEO_BASE_URL } from "@/lib/seo";
+import { buildPageMetadata } from "@/lib/seo";
type Props = {
params: Promise<{ locale: string }>;
@@ -11,28 +11,14 @@ type Props = {
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { locale } = await params;
const t = await getTranslations("donation.page");
- const title = t("title");
- const description = t("description");
- const url = getRouteAlternates(locale, "/donate");
- return {
- title,
- description,
- alternates: url,
- openGraph: {
- title,
- description,
- url: url.canonical,
- images: [
- {
- url: `${SEO_BASE_URL}/images/metadata/preview-openvid.jpg`,
- width: 1200,
- height: 630,
- alt: "OpenVid - Support the project",
- },
- ],
- },
- };
+ return buildPageMetadata({
+ locale,
+ path: "/donate",
+ title: t("title"),
+ description: t("description"),
+ imageAlt: "OpenVid — Support the project",
+ });
}
export interface DonationMethod {
diff --git a/app/[locale]/(home)/layout.tsx b/app/[locale]/(home)/layout.tsx
index a56d2d6..d7dfcf2 100644
--- a/app/[locale]/(home)/layout.tsx
+++ b/app/[locale]/(home)/layout.tsx
@@ -6,7 +6,6 @@ import RecordingOverlay from "@/app/components/ui/RecordingOverlay";
import { RecordingProvider } from "@/app/contexts/RecordingContext";
import { AuthProvider } from "@/app/contexts/useAuth";
import { ReactLenis } from "lenis/react";
-import "../../globals.css";
export default function HomeLayout({ children }: { children: React.ReactNode }) {
return (
diff --git a/app/[locale]/(home)/page.tsx b/app/[locale]/(home)/page.tsx
index 7424c70..753de27 100644
--- a/app/[locale]/(home)/page.tsx
+++ b/app/[locale]/(home)/page.tsx
@@ -1,111 +1,119 @@
import Hero from "@/app/components/ui/home/Hero";
import InteractiveRecordingSteps from "@/app/components/ui/home/RecordingSteps";
-import { StructuredData, generateWebAppSchema, generateOrganizationSchema, generateWebSiteSchema } from "@/app/components/seo/StructuredData";
-import type { Metadata } from 'next';
+import {
+ StructuredData,
+ generateWebAppSchema,
+ generateOrganizationSchema,
+ generateWebSiteSchema,
+} from "@/app/components/seo/StructuredData";
+import type { Metadata } from "next";
import DonationCard from "@/app/components/ui/home/DonationCard";
import VideoHero from "@/app/components/ui/home/VideoHero";
import BannerCTA from "@/app/components/ui/home/BannerCTA";
import FeaturesGrid from "@/app/components/ui/home/Featuresgrid";
import FeaturesShowcase from "@/app/components/ui/home/FeaturesShowcase";
import SocialReactions from "@/app/components/ui/home/SocialReactions";
+import { buildPageMetadata } from "@/lib/seo";
+import { setRequestLocale } from "next-intl/server";
type Props = {
params: Promise<{ locale: string }>;
};
-export async function generateMetadata({ params }: Props): Promise<Metadata> {
- const { locale } = await params;
- const baseUrl = 'https://openvid.dev';
-
- const metadata = {
- es: {
- title: 'Crea demos profesionales y edita videos en segundos',
- description: 'Editor de video online gratuito con IA. Graba pantalla, añade zooms cinemáticos, mockups profesionales y exporta en HD. Sin marca de agua.',
- keywords: ['editor de video', 'grabar pantalla', 'demos profesionales', 'zoom video', 'mockups', 'screen recorder', 'video editor online'],
- },
- en: {
- title: 'Create Professional Demos and Edit Videos in Seconds',
- description: 'Free AI-powered online video editor. Screen recorder, cinematic zooms, professional mockups, and HD export. No watermark.',
- keywords: ['video editor', 'screen recorder', 'professional demos', 'video zoom', 'mockups', 'online video editor', 'free video editor'],
- },
- ru: {
- title: 'Создавайте профессиональные демонстрации и редактируйте видео за секунды',
- description: 'Бесплатный онлайн-редактор видео с ИИ. Запись экрана, кинематические зумы, профессиональные макеты и экспорт в HD. Без водяного знака.',
- keywords: ['редактор видео', 'запись экрана', 'профессиональные демонстрации', 'зум видео', 'макеты', 'онлайн-редактор видео', 'бесплатный редактор видео'],
- },
- ko: {
- title: '몇 초 만에 전문적인 데모를 만들고 동영상을 편집하세요',
- description: '무료 AI 기반 온라인 동영상 에디터. 화면을 녹화하고 시네마틱 줌, 전문 목업을 추가해 HD로 내보내세요. 워터마크 없음.',
- keywords: ['동영상 에디터', '화면 녹화', '전문 데모', '동영상 줌', '목업', '온라인 동영상 에디터', '무료 동영상 에디터'],
- },
- };
-
- const { title, description, keywords } = metadata[locale as 'es' | 'en' | 'ru' | 'ko'] || metadata.es;
+const HOME_COPY = {
+ es: {
+ title: "Crea demos profesionales y edita videos en segundos",
+ description:
+ "Editor de video online gratuito con IA. Graba pantalla, zooms cinemáticos, mockups 3D y exporta en HD. Sin marca de agua.",
+ keywords: [
+ "editor de video",
+ "grabar pantalla",
+ "demos profesionales",
+ "zoom video",
+ "mockups 3D",
+ "screen recorder",
+ "video editor online",
+ "openvid",
+ ],
+ },
+ en: {
+ title: "Create Professional Demos and Edit Videos in Seconds",
+ description:
+ "Free AI-powered online video editor. Screen recorder, cinematic zooms, 3D mockups, and HD export. No watermark.",
+ keywords: [
+ "video editor",
+ "screen recorder",
+ "professional demos",
+ "video zoom",
+ "3D mockups",
+ "online video editor",
+ "free video editor",
+ "openvid",
+ ],
+ },
+ ru: {
+ title:
+ "Создавайте профессиональные демонстрации и редактируйте видео за секунды",
+ description:
+ "Бесплатный онлайн-редактор видео с ИИ. Запись экрана, кинематические зумы, 3D-макеты и экспорт в HD. Без водяного знака.",
+ keywords: [
+ "редактор видео",
+ "запись экрана",
+ "профессиональные демонстрации",
+ "зум видео",
+ "3D макеты",
+ "онлайн-редактор видео",
+ "openvid",
+ ],
+ },
+ ko: {
+ title: "몇 초 만에 전문적인 데모를 만들고 동영상을 편집하세요",
+ description:
+ "무료 AI 기반 온라인 동영상 에디터. 화면 녹화, 시네마틱 줌, 3D 목업, HD 내보내기. 워터마크 없음.",
+ keywords: [
+ "동영상 에디터",
+ "화면 녹화",
+ "전문 데모",
+ "동영상 줌",
+ "3D 목업",
+ "온라인 동영상 에디터",
+ "openvid",
+ ],
+ },
+} as const;
- const ogLocaleMap: Record<string, string> = {
- en: 'en_US',
- es: 'es_ES',
- ru: 'ru_RU',
- ko: 'ko_KR',
- };
- const currentOgLocale = ogLocaleMap[locale] || 'en_US';
- const alternateLocales = Object.values(ogLocaleMap).filter(loc => loc !== currentOgLocale);
+type HomeLocale = keyof typeof HOME_COPY;
- const url = `${baseUrl}/${locale}`;
+export async function generateMetadata({ params }: Props): Promise<Metadata> {
+ const { locale } = await params;
+ const copy = HOME_COPY[(locale as HomeLocale)] ?? HOME_COPY.en;
- return {
- title,
- description,
- keywords,
- alternates: {
- canonical: url,
- languages: {
- es: `${baseUrl}/es`,
- en: `${baseUrl}/en`,
- ru: `${baseUrl}/ru`,
- ko: `${baseUrl}/ko`,
- },
- },
- openGraph: {
- type: 'website',
- siteName: 'OpenVid',
- locale: currentOgLocale,
- alternateLocale: alternateLocales,
- url,
- title,
- description,
- images: [
- {
- url: `${baseUrl}/images/metadata/preview-openvid.jpg`,
- width: 1200,
- height: 630,
- alt: 'openvid - Professional Video Editor',
- },
- ],
- },
- twitter: {
- card: 'summary_large_image',
- site: '@openvid',
- creator: '@cristianolivera',
- title,
- description,
- images: [`${baseUrl}/images/metadata/preview-openvid.jpg`],
- },
- };
+ return buildPageMetadata({
+ locale,
+ path: "",
+ title: copy.title,
+ description: copy.description,
+ keywords: [...copy.keywords],
+ });
}
export default async function Home({ params }: Props) {
const { locale } = await params;
+ setRequestLocale(locale);
+ const schemaLocale = (locale in HOME_COPY ? locale : "en") as HomeLocale;
return (
<>
- <StructuredData data={generateWebAppSchema(locale as 'en' | 'es' | 'ru' | 'ko')} />
- <StructuredData data={generateWebSiteSchema(locale as 'en' | 'es' | 'ru' | 'ko')} />
+ <StructuredData data={generateWebAppSchema(schemaLocale)} />
+ <StructuredData data={generateWebSiteSchema(schemaLocale)} />
<StructuredData data={generateOrganizationSchema()} />
<div className="flex flex-col">
<div className="relative overflow-hidden bg-gradient-radial-primary w-full">
- <div className="absolute top-0 left-1/2 -translate-x-1/2 w-75 h-75 rounded-full bg-cyan-500/15 blur-[80px] pointer-events-none z-0" aria-hidden="true" />
+ <div
+ className="absolute top-0 left-1/2 -translate-x-1/2 w-75 h-75 rounded-full bg-cyan-500/15 blur-[80px] pointer-events-none z-0"
+ aria-hidden="true"
+ />
<section className="pt-32 pb-6 sm:pb-14" aria-label="Hero section">
<div className="max-w-6xl mx-auto px-6 text-center relative z-10">
<Hero />
@@ -142,4 +150,4 @@ export default async function Home({ params }: Props) {
</div>
</>
);
-}
\ No newline at end of file
+}
diff --git a/app/[locale]/(legal)/privacy/page.tsx b/app/[locale]/(legal)/privacy/page.tsx
index d6ad623..2851050 100644
--- a/app/[locale]/(legal)/privacy/page.tsx
+++ b/app/[locale]/(legal)/privacy/page.tsx
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
import { Icon } from "@iconify/react";
import { getLocale, getTranslations, setRequestLocale } from "next-intl/server";
import { Link } from "@/navigation";
-import { getRouteAlternates, SEO_BASE_URL } from "@/lib/seo";
+import { buildPageMetadata } from "@/lib/seo";
type Props = {
params: Promise<{ locale: string }>;
@@ -12,26 +12,14 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { locale } = await params;
const t = await getTranslations("privacy");
const description = t.raw("intro.content") as string;
- const url = getRouteAlternates(locale, "/privacy");
- return {
+ return buildPageMetadata({
+ locale,
+ path: "/privacy",
title: t("title"),
description,
- alternates: url,
- openGraph: {
- title: t("title"),
- description,
- url: url.canonical,
- images: [
- {
- url: `${SEO_BASE_URL}/images/metadata/preview-openvid.jpg`,
- width: 1200,
- height: 630,
- alt: "OpenVid - Privacy Policy",
- },
- ],
- },
- };
+ imageAlt: "OpenVid — Privacy Policy",
+ });
}
export default async function PrivacyPage({ params }: Props) {
diff --git a/app/[locale]/(legal)/terms/page.tsx b/app/[locale]/(legal)/terms/page.tsx
index 30ac724..18e91fa 100644
--- a/app/[locale]/(legal)/terms/page.tsx
+++ b/app/[locale]/(legal)/terms/page.tsx
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
import { Icon } from "@iconify/react";
import { getLocale, getTranslations, setRequestLocale } from "next-intl/server";
import { Link } from "@/navigation";
-import { getRouteAlternates, SEO_BASE_URL } from "@/lib/seo";
+import { buildPageMetadata } from "@/lib/seo";
type Props = {
params: Promise<{ locale: string }>;
@@ -12,26 +12,14 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { locale } = await params;
const t = await getTranslations("terms");
const description = t.raw("description.content") as string;
- const url = getRouteAlternates(locale, "/terms");
- return {
+ return buildPageMetadata({
+ locale,
+ path: "/terms",
title: t("title"),
description,
- alternates: url,
- openGraph: {
- title: t("title"),
- description,
- url: url.canonical,
- images: [
- {
- url: `${SEO_BASE_URL}/images/metadata/preview-openvid.jpg`,
- width: 1200,
- height: 630,
- alt: "OpenVid - Terms of Service",
- },
- ],
- },
- };
+ imageAlt: "OpenVid — Terms of Service",
+ });
}
export default async function TermsPage({ params }: Props) {
diff --git a/app/[locale]/layout.tsx b/app/[locale]/layout.tsx
index 2144340..f2186a8 100644
--- a/app/[locale]/layout.tsx
+++ b/app/[locale]/layout.tsx
@@ -1,18 +1,31 @@
-import { NextIntlClientProvider } from 'next-intl';
-import { getMessages, setRequestLocale } from 'next-intl/server';
-import { notFound } from 'next/navigation';
-import { locales, type Locale } from '@/i18n';
+import { NextIntlClientProvider } from "next-intl";
+import { getMessages, setRequestLocale } from "next-intl/server";
+import { notFound } from "next/navigation";
+import { defaultLocale, locales, type Locale } from "@/i18n";
import { TooltipProvider } from "@/components/ui/tooltip";
-import { Inter, Roboto, Poppins, Montserrat, DM_Sans } from "next/font/google";
-import type { Metadata, Viewport } from 'next';
-import { GoogleAnalytics } from '@next/third-parties/google';
+import { Inter, Roboto } from "next/font/google";
+import type { Metadata, Viewport } from "next";
+import { GoogleAnalytics } from "@next/third-parties/google";
+import {
+ buildPageMetadata,
+ getOgLocales,
+ getRouteAlternates,
+ SEO_BASE_URL,
+ SEO_OG_IMAGE,
+} from "@/lib/seo";
import "../globals.css";
-const inter = Inter({ subsets: ["latin"], variable: "--font-inter", display: "swap" });
-const roboto = Roboto({ subsets: ["latin"], weight: ["400", "500", "700"], variable: "--font-roboto", display: "swap" });
-const poppins = Poppins({ subsets: ["latin"], weight: ["400", "500", "700"], variable: "--font-poppins", display: "swap" });
-const montserrat = Montserrat({ subsets: ["latin"], weight: ["400", "500", "700"], variable: "--font-montserrat", display: "swap" });
-const dmSans = DM_Sans({ subsets: ["latin"], weight: ["400", "500", "700"], variable: "--font-dm-sans", display: "swap" });
+const inter = Inter({
+ subsets: ["latin"],
+ variable: "--font-inter",
+ display: "swap",
+});
+const roboto = Roboto({
+ subsets: ["latin"],
+ weight: ["400", "500", "700"],
+ variable: "--font-roboto",
+ display: "swap",
+});
export const viewport: Viewport = {
width: "device-width",
@@ -32,51 +45,46 @@ type Props = {
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { locale } = await params;
- const baseUrl = 'https://openvid.dev';
+ const { locale: ogLocale, alternateLocale } = getOgLocales(locale);
+ const alternates = getRouteAlternates(locale);
- const ogLocaleMap: Record<string, string> = {
- en: 'en_US',
- es: 'es_ES',
- ru: 'ru_RU',
- ko: 'ko_KR'
- };
-
- const currentOgLocale = ogLocaleMap[locale] || 'en_US';
- const alternateLocales = locales.filter(l => l !== locale).map(l => ogLocaleMap[l]);
+ const defaults = buildPageMetadata({
+ locale,
+ title: "Create Cinematic Product Demos in Your Browser",
+ description:
+ "Free, privacy-first, browser-based video editor. Turn screen recordings into professional product demos with 3D mockups, cinematic zooms, and 4K export.",
+ keywords: [
+ "openvid",
+ "product demo creator",
+ "browser video editor",
+ "screen recorder",
+ "3D device mockups",
+ "cinematic video zooms",
+ "local video rendering",
+ "privacy-first video tool",
+ "SaaS marketing video",
+ ],
+ });
return {
- metadataBase: new URL(baseUrl),
+ ...defaults,
+ metadataBase: new URL(SEO_BASE_URL),
title: {
default: "OpenVid | Create Cinematic Product Demos in Your Browser",
template: "%s | OpenVid",
},
- description: "Free, privacy-first, browser-based video editor. Turn standard screen recordings into professional product demos with 3D device mockups, cinematic zooms, and 4K export.",
applicationName: "OpenVid",
- generator: "Next.js",
category: "design tool",
manifest: "/site.webmanifest",
- keywords: [
- "openvid", "product demo creator", "browser video editor", "screen recorder",
- "3D device mockups", "cinematic video zooms", "local video rendering",
- "privacy-first video tool", "ffmpeg.wasm editor", "SaaS marketing video", "Cristian Olivera"
+ authors: [
+ { name: "Cristian Olivera", url: "https://github.com/CristianOlivera1" },
],
- authors: [{ name: "Cristian Olivera", url: "https://github.com/CristianOlivera1" }],
creator: "Cristian Olivera",
publisher: "OpenVid",
- robots: {
- index: true,
- follow: true,
- nocache: false,
- googleBot: {
- index: true,
- follow: true,
- "max-video-preview": -1,
- "max-image-preview": "large",
- "max-snippet": -1,
- },
- },
icons: {
- icon: "/images/metadata/favicon.svg",
+ icon: [
+ { url: "/images/metadata/favicon.svg", type: "image/svg+xml" },
+ ],
shortcut: "/images/metadata/shortcut.svg",
apple: "/images/metadata/apple.svg",
},
@@ -85,29 +93,24 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
statusBarStyle: "black-translucent",
capable: true,
},
- twitter: {
- card: "summary_large_image",
- creator: "@cristianolivera",
- site: "@openvid",
- },
- other: {
- "msapplication-TileColor": "#000000",
- "format-detection": "telephone=no",
- },
+ alternates,
openGraph: {
- type: "website",
- siteName: "OpenVid",
+ ...defaults.openGraph,
+ locale: ogLocale,
+ alternateLocale,
images: [
{
- url: "/images/metadata/preview-openvid.jpg",
- width: 1200,
- height: 630,
- alt: "OpenVid - 3D Mockups and Cinematic Demo Creator",
- type: "image/jpeg",
+ url: SEO_OG_IMAGE.url,
+ width: SEO_OG_IMAGE.width,
+ height: SEO_OG_IMAGE.height,
+ alt: SEO_OG_IMAGE.alt,
+ type: SEO_OG_IMAGE.type,
},
],
- locale: currentOgLocale,
- alternateLocale: alternateLocales,
+ },
+ other: {
+ "msapplication-TileColor": "#000000",
+ "format-detection": "telephone=no",
},
};
}
@@ -118,7 +121,7 @@ export function generateStaticParams() {
export default async function LocaleLayout({
children,
- params
+ params,
}: {
children: React.ReactNode;
params: Promise<{ locale: string }>;
@@ -131,6 +134,9 @@ export default async function LocaleLayout({
setRequestLocale(locale);
const messages = (await getMessages()) as Record<string, unknown>;
+
+ // Only ship namespaces the marketing chrome actually needs.
+ // Editor pages load their own messages via next-intl where required.
const publicMessages = {
header: messages.header,
footer: messages.footer,
@@ -145,26 +151,24 @@ export default async function LocaleLayout({
donation: messages.donation,
notFound: messages.notFound,
};
- const isProduction = process.env.NODE_ENV === 'production';
+
+ const isProduction = process.env.NODE_ENV === "production";
const gaId = process.env.NEXT_PUBLIC_GA_ID;
return (
- <html lang={locale}>
+ <html lang={locale || defaultLocale} suppressHydrationWarning>
<body
- className={`
- ${inter.variable} ${roboto.variable} ${poppins.variable}
- ${montserrat.variable} ${dmSans.variable} ${inter.className}
- antialiased dark
- `}
+ className={`${inter.variable} ${roboto.variable} ${inter.className} antialiased dark`}
>
- <meta httpEquiv="content-language" content={locale} />
- <NextIntlClientProvider key={locale} messages={publicMessages} locale={locale}>
- <TooltipProvider delayDuration={200}>
- {children}
- </TooltipProvider>
+ <NextIntlClientProvider
+ key={locale}
+ messages={publicMessages}
+ locale={locale}
+ >
+ <TooltipProvider delayDuration={200}>{children}</TooltipProvider>
</NextIntlClientProvider>
</body>
- {isProduction && gaId && <GoogleAnalytics gaId={gaId} />}
+ {isProduction && gaId ? <GoogleAnalytics gaId={gaId} /> : null}
</html>
);
-}
\ No newline at end of file
+}
diff --git a/app/components/seo/StructuredData.tsx b/app/components/seo/StructuredData.tsx
index 557cb61..edaeac7 100644
--- a/app/components/seo/StructuredData.tsx
+++ b/app/components/seo/StructuredData.tsx
@@ -143,7 +143,7 @@ export function generateWebAppSchema(locale: 'es' | 'en' | 'ru' | 'ko'): WebAppl
priceCurrency: 'USD',
},
description,
- url: baseUrl,
+ url: `${baseUrl}/${locale}`,
inLanguage: locale,
image: `${baseUrl}/images/metadata/preview-openvid.jpg`,
author: {
@@ -182,7 +182,7 @@ export function generateWebSiteSchema(locale: 'es' | 'en' | 'ru' | 'ko'): WebSit
'@type': 'WebSite',
name: 'OpenVid',
alternateName: 'openvid',
- url: 'https://openvid.dev',
+ url: `https://openvid.dev/${locale}`,
inLanguage: locale,
publisher: {
'@type': 'Organization',
diff --git a/app/contexts/useAuth.tsx b/app/contexts/useAuth.tsx
index 211df0c..41d25b3 100644
--- a/app/contexts/useAuth.tsx
+++ b/app/contexts/useAuth.tsx
@@ -1,6 +1,13 @@
"use client";
-import { createContext, useContext, useEffect, useState, useCallback } from "react";
+import {
+ createContext,
+ useContext,
+ useEffect,
+ useState,
+ useCallback,
+ useMemo,
+} from "react";
import { createClient } from "@/utils/supabase/client";
import type { User, Session, AuthChangeEvent } from "@supabase/supabase-js";
@@ -27,85 +34,80 @@ interface AuthContextType {
const AuthContext = createContext<AuthContextType | undefined>(undefined);
+const PROFILE_REFRESH_EVENTS = new Set<AuthChangeEvent>([
+ "INITIAL_SESSION",
+ "SIGNED_IN",
+ "USER_UPDATED",
+ "PASSWORD_RECOVERY",
+]);
+
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [profile, setProfile] = useState<UserProfile | null>(null);
const [session, setSession] = useState<Session | null>(null);
const [loading, setLoading] = useState(true);
- const supabase = createClient();
- const fetchProfile = useCallback(async (userId: string) => {
- try {
- const { data, error } = await supabase
- .from("user_profiles")
- .select("*")
- .eq("id", userId)
- .single();
+ const supabase = useMemo(() => createClient(), []);
+
+ const fetchProfile = useCallback(
+ async (userId: string) => {
+ try {
+ const { data, error } = await supabase
+ .from("user_profiles")
+ .select("*")
+ .eq("id", userId)
+ .single();
+
+ if (error) {
+ console.error("Error fetching profile:", error);
+ return null;
+ }
- if (error) {
+ return data as UserProfile;
+ } catch (error) {
console.error("Error fetching profile:", error);
return null;
}
+ },
+ [supabase],
+ );
- return data as UserProfile;
- } catch (error) {
- console.error("Error fetching profile:", error);
- return null;
- }
- }, [supabase]);
-
- const refreshProfile = async () => {
- if (user) {
- const profileData = await fetchProfile(user.id);
- setProfile(profileData);
- }
- };
+ const refreshProfile = useCallback(async () => {
+ if (!user) return;
+ const profileData = await fetchProfile(user.id);
+ setProfile(profileData);
+ }, [user, fetchProfile]);
useEffect(() => {
let mounted = true;
- const initializeAuth = async () => {
- try {
- const {
- data: { session: initialSession },
- } = await supabase.auth.getSession();
-
+ const {
+ data: { subscription },
+ } = supabase.auth.onAuthStateChange(
+ (event: AuthChangeEvent, newSession: Session | null) => {
if (!mounted) return;
- setSession(initialSession);
- setUser(initialSession?.user ?? null);
+ setSession(newSession);
+ setUser(newSession?.user ?? null);
setLoading(false);
- if (initialSession?.user) {
- const profileData = await fetchProfile(initialSession.user.id);
- if (mounted) {
- setProfile(profileData);
- }
+ if (event === "TOKEN_REFRESHED") {
+ return;
}
- } catch (error) {
- console.error("Error initializing auth:", error);
- if (mounted) setLoading(false);
- }
- };
- initializeAuth();
+ if (event === "SIGNED_OUT" || !newSession?.user) {
+ setProfile(null);
+ return;
+ }
- const {
- data: { subscription },
- } = supabase.auth.onAuthStateChange(async (_event: AuthChangeEvent, newSession: Session | null) => {
- setSession(newSession);
- setUser(newSession?.user ?? null);
-
- if (newSession?.user) {
- fetchProfile(newSession.user.id).then((profileData) => {
- if (mounted) setProfile(profileData);
- });
- } else {
- setProfile(null);
- }
-
- setLoading(false);
- });
+ if (PROFILE_REFRESH_EVENTS.has(event)) {
+ const userId = newSession.user.id;
+ void fetchProfile(userId).then((profileData) => {
+ if (mounted) setProfile(profileData);
+ });
+ }
+ },
+ );
return () => {
mounted = false;
@@ -113,19 +115,25 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
};
}, [supabase, fetchProfile]);
- const signOut = async () => {
- await supabase.auth.signOut();
+ const signOut = useCallback(async () => {
+ // Optimistic clear for snappy UI; SIGNED_OUT confirms via the listener.
setUser(null);
setProfile(null);
setSession(null);
- };
+
+ const { error } = await supabase.auth.signOut();
+ if (error) {
+ console.error("Error signing out:", error);
+ }
+ }, [supabase]);
+
+ const value = useMemo(
+ () => ({ user, profile, session, loading, signOut, refreshProfile }),
+ [user, profile, session, loading, signOut, refreshProfile],
+ );
return (
- <AuthContext.Provider
- value={{ user, profile, session, loading, signOut, refreshProfile }}
- >
- {children}
- </AuthContext.Provider>
+ <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
);
}
@@ -135,4 +143,4 @@ export function useAuth() {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
-}
\ No newline at end of file
+}