Create professional demos and 3D mockups in seconds, directly in your browser
feat(seo): enhance SEO functionality with locale handling and metadata generation feat(proxy): improve session management and user authentication flow refactor(middleware): streamline session update logic and cookie handling fix(server): correct cookie setting in Supabase client creation
CristianOlivera11d258fa5d11a
diff --git a/lib/seo.ts b/lib/seo.tsindex 769497d..f00f43d 100644--- a/lib/seo.ts+++ b/lib/seo.ts@@ -1,15 +1,118 @@-import { locales } from '@/i18n';+import type { Metadata } from "next";+import { defaultLocale, locales } from "@/i18n";-export const SEO_BASE_URL = 'https://openvid.dev';+export const SEO_BASE_URL = "https://openvid.dev";-export function getRouteAlternates(locale: string, path: string = '') {+export const SEO_OG_IMAGE = {+ url: `${SEO_BASE_URL}/images/metadata/preview-openvid.jpg`,+ width: 1200,+ height: 630,+ type: "image/jpeg",+ alt: "OpenVid — free browser video editor with cinematic zooms and 3D mockups",+} as const;++export const OG_LOCALE_MAP: Record<string, string> = {+ en: "en_US",+ es: "es_ES",+ ru: "ru_RU",+ ko: "ko_KR",+};++export function getLocaleUrl(locale: string, path: string = ""): string {+ const normalized = path === "/" ? "" : path;+ return `${SEO_BASE_URL}/${locale}${normalized}`;+}++export function getRouteAlternates(locale: string, path: string = "") {const languages: Record<string, string> = {};- locales.forEach((loc) => {- languages[loc] = `${SEO_BASE_URL}/${loc}${path}`;- });++ for (const loc of locales) {+ languages[loc] = getLocaleUrl(loc, path);+ }++ languages["x-default"] = getLocaleUrl(defaultLocale, path);return {- canonical: `${SEO_BASE_URL}/${locale}${path}`,+ canonical: getLocaleUrl(locale, path),languages,};-}\ No newline at end of file+}++export function getOgLocales(locale: string) {+ const current = OG_LOCALE_MAP[locale] ?? OG_LOCALE_MAP[defaultLocale];+ const alternateLocale = Object.values(OG_LOCALE_MAP).filter(+ (code) => code !== current,+ );+ return { locale: current, alternateLocale };+}++type BuildPageMetadataInput = {+ locale: string;+ path?: string;+ title: string;+ description: string;+ keywords?: string[];+ imageAlt?: string;+ noIndex?: boolean;+};++export function buildPageMetadata({+ locale,+ path = "",+ title,+ description,+ keywords,+ imageAlt,+ noIndex = false,+}: BuildPageMetadataInput): Metadata {+ const alternates = getRouteAlternates(locale, path);+ const { locale: ogLocale, alternateLocale } = getOgLocales(locale);+ const image = {+ url: SEO_OG_IMAGE.url,+ width: SEO_OG_IMAGE.width,+ height: SEO_OG_IMAGE.height,+ type: SEO_OG_IMAGE.type,+ alt: imageAlt ?? SEO_OG_IMAGE.alt,+ };++ return {+ title,+ description,+ keywords,+ alternates,+ robots: noIndex+ ? { index: false, follow: false }+ : {+ index: true,+ follow: true,+ googleBot: {+ index: true,+ follow: true,+ "max-video-preview": -1,+ "max-image-preview": "large",+ "max-snippet": -1,+ },+ },+ openGraph: {+ type: "website",+ siteName: "OpenVid",+ locale: ogLocale,+ alternateLocale,+ url: alternates.canonical,+ title,+ description,+ images: [image],+ },+ twitter: {+ card: "summary_large_image",+ site: "@openvid",+ creator: "@cristianolivera",+ title,+ description,+ images: {+ url: SEO_OG_IMAGE.url,+ alt: image.alt,+ },+ },+ };+}diff --git a/proxy.ts b/proxy.tsindex 73ab6f1..61d6255 100644--- a/proxy.ts+++ b/proxy.ts@@ -1,34 +1,92 @@-import { type NextRequest } from "next/server";-import createIntlMiddleware from 'next-intl/middleware';-import { locales, defaultLocale } from './i18n';-import { updateSession } from "@/utils/supabase/middleware";+import { type NextRequest, NextResponse } from "next/server";+import createIntlMiddleware from "next-intl/middleware";+import { locales, defaultLocale } from "./i18n";+import {+ updateSession,+ enforceAuthRoutes,+ shouldRefreshSession,+} from "@/utils/supabase/middleware";const intlMiddleware = createIntlMiddleware({locales,defaultLocale,- localePrefix: 'always',- localeDetection: true+ localePrefix: "always",+ localeDetection: true,});export default async function proxy(request: NextRequest) {- const country = request.headers.get('x-vercel-ip-country') || 'UNKNOWN';+ const country = request.headers.get("x-vercel-ip-country") || "UNKNOWN";++ const needsAuth = shouldRefreshSession(request);++ if (!needsAuth) {+ const intlResponse = intlMiddleware(request);+ intlResponse.headers.set("x-user-country", country);+ return intlResponse;+ }++ const { user, applyAuthCookies } = await updateSession(request);++ const authRedirect = enforceAuthRoutes(request, user);+ if (authRedirect) {+ applyAuthCookies(authRedirect);+ authRedirect.headers.set("x-user-country", country);+ return authRedirect;+ }const intlResponse = intlMiddleware(request);- intlResponse.headers.set('x-user-country', country);+ const didSetAuthCookies = applyAuthCookies(intlResponse);+ intlResponse.headers.set("x-user-country", country);- const supabaseResponse = await updateSession(request);- if (supabaseResponse.headers.has('location')) {- return supabaseResponse;+ if (didSetAuthCookies) {+ return forwardWithRefreshedRequest(request, intlResponse, country);}- supabaseResponse.cookies.getAll().forEach((cookie) => {- intlResponse.cookies.set(cookie.name, cookie.value);- });return intlResponse;}+function forwardWithRefreshedRequest(+ request: NextRequest,+ source: NextResponse,+ country: string,+): NextResponse {+ if (source.status >= 300 && source.status < 400) {+ source.headers.set("x-user-country", country);+ return source;+ }++ const finalResponse = NextResponse.next({+ request: {+ headers: request.headers,+ },+ });++ source.headers.forEach((value, key) => {+ if (key.toLowerCase() === "set-cookie") return;+ finalResponse.headers.set(key, value);+ });++ const setCookies =+ typeof source.headers.getSetCookie === "function"+ ? source.headers.getSetCookie()+ : [];++ if (setCookies.length > 0) {+ for (const cookie of setCookies) {+ finalResponse.headers.append("Set-Cookie", cookie);+ }+ } else {+ source.cookies.getAll().forEach(({ name, value }) => {+ finalResponse.cookies.set(name, value);+ });+ }++ finalResponse.headers.set("x-user-country", country);+ return finalResponse;+}+export const config = {matcher: [- '/((?!api|ffmpeg|models|hdri|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|site.webmanifest|.*\\.(?:svg|png|jpg|jpeg|gif|webp|mp4|avif|webm|wasm|js|glb|gltf|webmanifest|json)$).*)'+ "/((?!api|ffmpeg|models|hdri|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|site.webmanifest|.*\\.(?:svg|png|jpg|jpeg|gif|webp|mp4|avif|webm|wasm|js|glb|gltf|webmanifest|json)$).*)",],};diff --git a/utils/supabase/middleware.ts b/utils/supabase/middleware.tsindex 4f0bbdc..0e65597 100644--- a/utils/supabase/middleware.ts+++ b/utils/supabase/middleware.ts@@ -1,4 +1,5 @@import { createServerClient } from "@supabase/ssr";+import { type User } from "@supabase/supabase-js";import { type NextRequest, NextResponse } from "next/server";const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;@@ -8,33 +9,69 @@ if (!supabaseUrl || !supabaseKey) {throw new Error("Missing Supabase environment variables");}-export const updateSession = async (request: NextRequest) => {- const pathname = request.nextUrl.pathname;+type CookieToSet = {+ name: string;+ value: string;+ options?: Parameters<NextResponse["cookies"]["set"]>[2];+};++export type SessionUpdateResult = {+ user: User | null;+ applyAuthCookies: (target: NextResponse) => boolean;+};++function isVideoEditorPath(pathname: string, searchParams: URLSearchParams) {+ return pathname.endsWith("/editor") && searchParams.get("mode") !== "photo";+}++function isLoginPath(pathname: string) {+ return pathname.endsWith("/login");+}- const isVideoEditor = pathname.endsWith("/editor") && request.nextUrl.searchParams.get("mode") !== "photo";- const isLogin = pathname.endsWith("/login");+export function hasSupabaseAuthCookie(request: NextRequest): boolean {+ return request.cookies+ .getAll()+ .some((cookie) => cookie.name.includes("-auth-token"));+}- if (!isVideoEditor && !isLogin) {- return NextResponse.next({ request });+export function shouldRefreshSession(request: NextRequest): boolean {+ const { pathname, searchParams } = request.nextUrl;+ if (isVideoEditorPath(pathname, searchParams) || isLoginPath(pathname)) {+ return true;}+ return hasSupabaseAuthCookie(request);+}- let supabaseResponse = NextResponse.next({- request,- });+export function getSafeInternalPath(+ value: string | null | undefined,+ fallback: string,+): string {+ if (!value) return fallback;+ if (!value.startsWith("/") || value.startsWith("//") || value.includes("://")) {+ return fallback;+ }+ return value;+}++export async function updateSession(+ request: NextRequest,+): Promise<SessionUpdateResult> {+ const cookiesToApply: CookieToSet[] = [];- const supabase = createServerClient(supabaseUrl, supabaseKey, {+ const supabase = createServerClient(supabaseUrl!, supabaseKey!, {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 }) => {+ request.cookies.set(name, value);+ });++ cookiesToApply.length = 0;+ cookiesToSet.forEach(({ name, value, options }) => {+ cookiesToApply.push({ name, value, options });});- cookiesToSet.forEach(({ name, value, options }) =>- supabaseResponse.cookies.set(name, value, options)- );},},});@@ -43,24 +80,54 @@ export const updateSession = async (request: NextRequest) => {data: { user },} = await supabase.auth.getUser();- if (!user && isVideoEditor) {+ const applyAuthCookies = (target: NextResponse): boolean => {+ if (cookiesToApply.length === 0) return false;++ cookiesToApply.forEach(({ name, value, options }) => {+ target.cookies.set(name, value, options);+ });+ return true;+ };++ return { user, applyAuthCookies };+}++export function enforceAuthRoutes(+ request: NextRequest,+ user: User | null,+): NextResponse | null {+ const pathname = request.nextUrl.pathname;+ const { searchParams } = request.nextUrl;++ if (!user && isVideoEditorPath(pathname, searchParams)) {const url = request.nextUrl.clone();- const redirectedFrom = `${request.nextUrl.pathname}${request.nextUrl.search}`;+ const redirectedFrom = `${pathname}${request.nextUrl.search}`;+url.pathname = pathname.replace(/\/editor$/, "/login");url.search = "";url.searchParams.set("redirectedFrom", redirectedFrom);- if (request.nextUrl.searchParams.get("autoupload") === "1") {++ if (searchParams.get("autoupload") === "1") {url.searchParams.set("autoupload", "1");}+return NextResponse.redirect(url);}- if (user && pathname.endsWith("/login")) {+ if (user && isLoginPath(pathname)) {+ const fallback = pathname.replace(/\/login$/, "/editor");+ const destination = getSafeInternalPath(+ searchParams.get("redirectedFrom"),+ fallback,+ );+const url = request.nextUrl.clone();- url.pathname = pathname.replace("/login", "/editor");+ const destUrl = new URL(destination, request.nextUrl.origin);+ url.pathname = destUrl.pathname;+ url.search = destUrl.search;return NextResponse.redirect(url);}- return supabaseResponse;-};+ return null;+}diff --git a/utils/supabase/server.ts b/utils/supabase/server.tsindex 6046bd7..fea891f 100644--- a/utils/supabase/server.ts+++ b/utils/supabase/server.ts@@ -19,7 +19,7 @@ export const createClient = async () => {setAll(cookiesToSet) {try {cookiesToSet.forEach(({ name, value, options }) =>- cookieStore.set(name, value, options)+ cookieStore.set(name, value, options),);} catch {