Skip to content

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

security: move provider API keys server-side

PrivateKey90525bc05db2
diff --git a/.env.example b/.env.example
index 5085959..f190edf 100644
--- a/.env.example
+++ b/.env.example
@@ -1,8 +1,6 @@
-NEXT_PUBLIC_UNSPLASH_ACCESS_KEY=x.y.z
-NEXT_PUBLIC_UNSPLASH_SECRET_KEY=x.y.z
-NEXT_PUBLIC_PEXELS_API_KEY=x.y.z
-NEXT_PUBLIC_PIXABAY_API_KEY=x.y.z
-
-# Supabase Configuration
-NEXT_PUBLIC_SUPABASE_URL=x.y.z
-NEXT_PUBLIC_SUPABASE_ANON_KEY=x.y.z
\ No newline at end of file
+# Optional - only needed for the in-editor photo picker (Unsplash/Pexels/Pixabay).
+# All keys are read server-side, so they never reach the client bundle.
+# Without these the app still runs; only the photo picker returns empty results.
+UNSPLASH_ACCESS_KEY=
+PEXELS_API_KEY=
+PIXABAY_API_KEY=
diff --git a/app/api/photos/route.ts b/app/api/photos/route.ts
new file mode 100644
index 0000000..168bd37
--- /dev/null
+++ b/app/api/photos/route.ts
@@ -0,0 +1,209 @@
+import { NextResponse } from "next/server";
+import { env } from "@/app/config/env";
+
+export interface UnifiedPhoto {
+ id: string;
+ urls: { regular: string; small: string };
+ alt: string;
+ photographer: string;
+ color: string;
+ width: number;
+ height: number;
+}
+
+type Provider = "unsplash" | "pexels" | "pixabay";
+const PROVIDERS: Provider[] = ["unsplash", "pexels", "pixabay"];
+
+let providerIndex = 0;
+function getNextProvider(): Provider {
+ const provider = PROVIDERS[providerIndex];
+ providerIndex = (providerIndex + 1) % PROVIDERS.length;
+ return provider;
+}
+
+interface UnsplashPhoto {
+ id: string;
+ urls: { regular: string; small: string };
+ alt_description: string | null;
+ user: { name: string };
+ color: string;
+ width: number;
+ height: number;
+}
+
+async function fetchUnsplash(query: string, page: number, perPage: number): Promise<UnifiedPhoto[]> {
+ if (!env.unsplash.accessKey) return [];
+ const url = `https://api.unsplash.com/search/photos?query=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}&orientation=landscape`;
+ try {
+ const res = await fetch(url, {
+ headers: { Authorization: `Client-ID ${env.unsplash.accessKey}` },
+ });
+ if (!res.ok) return [];
+ const data = await res.json();
+ const results: UnsplashPhoto[] = data.results ?? [];
+ return results.map((photo) => ({
+ id: `unsplash-${photo.id}`,
+ urls: { regular: photo.urls.regular, small: photo.urls.small },
+ alt: photo.alt_description ?? "",
+ photographer: photo.user.name,
+ color: photo.color,
+ width: photo.width,
+ height: photo.height,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+interface PexelsPhoto {
+ id: number;
+ width: number;
+ height: number;
+ photographer: string;
+ avg_color: string;
+ src: { large: string; medium: string };
+ alt: string;
+}
+
+async function fetchPexelsRaw(url: string): Promise<UnifiedPhoto[]> {
+ if (!env.pexels.apiKey) return [];
+ try {
+ const res = await fetch(url, {
+ headers: { Authorization: env.pexels.apiKey },
+ });
+ if (!res.ok) return [];
+ const data = await res.json();
+ const results: PexelsPhoto[] = data.photos ?? [];
+ return results.map((photo) => ({
+ id: `pexels-${photo.id}`,
+ urls: { regular: photo.src.large, small: photo.src.medium },
+ alt: photo.alt || "",
+ photographer: photo.photographer,
+ color: photo.avg_color,
+ width: photo.width,
+ height: photo.height,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+async function fetchPexels(query: string, page: number, perPage: number): Promise<UnifiedPhoto[]> {
+ const url = `https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}&orientation=landscape`;
+ return fetchPexelsRaw(url);
+}
+
+interface PixabayPhoto {
+ id: number;
+ imageWidth: number;
+ imageHeight: number;
+ user: string;
+ tags: string;
+ webformatURL: string;
+ largeImageURL: string;
+}
+
+async function fetchPixabay(query: string, page: number, perPage: number): Promise<UnifiedPhoto[]> {
+ if (!env.pixabay.apiKey) return [];
+ const url = `https://pixabay.com/api/?key=${env.pixabay.apiKey}&q=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}&orientation=horizontal&image_type=photo`;
+ try {
+ const res = await fetch(url);
+ if (!res.ok) return [];
+ const data = await res.json();
+ const results: PixabayPhoto[] = data.hits ?? [];
+ return results.map((photo) => ({
+ id: `pixabay-${photo.id}`,
+ urls: { regular: photo.largeImageURL, small: photo.webformatURL },
+ alt: photo.tags,
+ photographer: photo.user,
+ color: "#1a1a1a",
+ width: photo.imageWidth,
+ height: photo.imageHeight,
+ }));
+ } catch {
+ return [];
+ }
+}
+
+async function fetchUnsplashCurated(page: number, perPage: number): Promise<UnifiedPhoto[]> {
+ const queries = [
+ "blur gradient", "mesh gradient", "dark minimal wallpaper", "neon city night",
+ "abstract wave dark", "geometric dark background",
+ "deep space stars", "aurora sky", "minimal texture dark",
+ ];
+ const query = queries[Math.floor(Math.random() * queries.length)];
+ return fetchUnsplash(query, page, perPage);
+}
+
+async function fetchPexelsCurated(page: number, perPage: number): Promise<UnifiedPhoto[]> {
+ const url = `https://api.pexels.com/v1/curated?page=${page}&per_page=${perPage}`;
+ const results = await fetchPexelsRaw(url);
+ return results.filter((photo) => photo.width >= photo.height);
+}
+
+async function fetchPixabayCurated(page: number, perPage: number): Promise<UnifiedPhoto[]> {
+ const queries = [
+ "blur gradient", "dark minimal", "city dark", "blurred",
+ "night sky", "minimalist background", "wallpaper sky",
+ ];
+ const query = queries[Math.floor(Math.random() * queries.length)];
+ return fetchPixabay(query, page, perPage);
+}
+
+const discoveryCache: { photos: UnifiedPhoto[]; timestamp: number } = {
+ photos: [],
+ timestamp: 0,
+};
+const DISCOVERY_TTL = 5 * 60 * 1000;
+
+async function getDiscovery(): Promise<UnifiedPhoto[]> {
+ if (
+ discoveryCache.photos.length > 0 &&
+ Date.now() - discoveryCache.timestamp < DISCOVERY_TTL
+ ) {
+ return [...discoveryCache.photos].sort(() => Math.random() - 0.5);
+ }
+
+ const [unsplashPhotos, pexelsPhotos, pixabayPhotos] = await Promise.all([
+ fetchUnsplashCurated(1, 7).catch(() => []),
+ fetchPexelsCurated(1, 7).catch(() => []),
+ fetchPixabayCurated(1, 6).catch(() => []),
+ ]);
+
+ const allPhotos = [...unsplashPhotos, ...pexelsPhotos, ...pixabayPhotos];
+ const shuffled = allPhotos.sort(() => Math.random() - 0.5);
+
+ discoveryCache.photos = shuffled;
+ discoveryCache.timestamp = Date.now();
+
+ return shuffled;
+}
+
+async function getSearch(query: string, page: number, perPage: number): Promise<UnifiedPhoto[]> {
+ const provider = getNextProvider();
+ switch (provider) {
+ case "unsplash": return fetchUnsplash(query, page, perPage);
+ case "pexels": return fetchPexels(query, page, perPage);
+ case "pixabay": return fetchPixabay(query, page, perPage);
+ }
+}
+
+export async function GET(request: Request) {
+ const { searchParams } = new URL(request.url);
+ const mode = searchParams.get("mode") ?? "search";
+ const query = searchParams.get("q") ?? "";
+ const page = Math.max(1, Number(searchParams.get("page") ?? "1") || 1);
+ const perPage = Math.min(50, Math.max(1, Number(searchParams.get("perPage") ?? "20") || 20));
+
+ if (mode === "discovery") {
+ const photos = await getDiscovery();
+ return NextResponse.json({ photos });
+ }
+
+ if (!query) {
+ return NextResponse.json({ photos: [] });
+ }
+
+ const photos = await getSearch(query, page, perPage);
+ return NextResponse.json({ photos });
+}
diff --git a/app/config/env.ts b/app/config/env.ts
index 76231ef..bd4e6b7 100644
--- a/app/config/env.ts
+++ b/app/config/env.ts
@@ -1,16 +1,11 @@
export const env = {
unsplash: {
- accessKey: process.env.NEXT_PUBLIC_UNSPLASH_ACCESS_KEY ?? "",
- secretKey: process.env.NEXT_PUBLIC_UNSPLASH_SECRET_KEY ?? "",
+ accessKey: process.env.UNSPLASH_ACCESS_KEY ?? "",
},
pexels: {
- apiKey: process.env.NEXT_PUBLIC_PEXELS_API_KEY ?? "",
+ apiKey: process.env.PEXELS_API_KEY ?? "",
},
pixabay: {
- apiKey: process.env.NEXT_PUBLIC_PIXABAY_API_KEY ?? "",
+ apiKey: process.env.PIXABAY_API_KEY ?? "",
},
- supabase: {
- url: process.env.NEXT_PUBLIC_SUPABASE_URL ?? "",
- publishableKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? "",
- },
-} as const;
\ No newline at end of file
+} as const;
diff --git a/lib/photo-providers.ts b/lib/photo-providers.ts
index ef9d0b7..ceaab11 100644
--- a/lib/photo-providers.ts
+++ b/lib/photo-providers.ts
@@ -1,5 +1,3 @@
-import { env } from "@/app/config/env";
-
export interface UnifiedPhoto {
id: string;
urls: {
@@ -13,218 +11,34 @@ export interface UnifiedPhoto {
height: number;
}
-export type PhotoProvider = "unsplash" | "pexels" | "pixabay";
-
-let providerIndex = 0;
-const providers: PhotoProvider[] = ["unsplash", "pexels", "pixabay"];
-
-function getNextProvider(): PhotoProvider {
- const provider = providers[providerIndex];
- providerIndex = (providerIndex + 1) % providers.length;
- return provider;
-}
-
-interface UnsplashPhoto {
- id: string;
- urls: { regular: string; small: string };
- alt_description: string | null;
- user: { name: string };
- color: string;
- width: number;
- height: number;
-}
-
-async function fetchUnsplash(query: string, page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
- const url = `https://api.unsplash.com/search/photos?query=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}&orientation=landscape`;
- try {
- const res = await fetch(url, {
- headers: { Authorization: `Client-ID ${env.unsplash.accessKey}` },
- });
- if (!res.ok) return [];
- const data = await res.json();
- const results: UnsplashPhoto[] = data.results ?? [];
- return results.map((photo) => ({
- id: `unsplash-${photo.id}`,
- urls: {
- regular: photo.urls.regular,
- small: photo.urls.small,
- },
- alt: photo.alt_description ?? "",
- photographer: photo.user.name,
- color: photo.color,
- width: photo.width,
- height: photo.height,
- }));
- } catch {
- return [];
- }
-}
-
-interface PexelsPhoto {
- id: number;
- width: number;
- height: number;
- photographer: string;
- avg_color: string;
- src: {
- large: string;
- medium: string;
- };
- alt: string;
-}
-
-async function fetchPexels(query: string, page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
- const url = `https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}&orientation=landscape`;
- try {
- const res = await fetch(url, {
- headers: { Authorization: env.pexels.apiKey },
- });
- if (!res.ok) return [];
- const data = await res.json();
- const results: PexelsPhoto[] = data.photos ?? [];
- return results.map((photo) => ({
- id: `pexels-${photo.id}`,
- urls: {
- regular: photo.src.large,
- small: photo.src.medium,
- },
- alt: photo.alt || "",
- photographer: photo.photographer,
- color: photo.avg_color,
- width: photo.width,
- height: photo.height,
- }));
- } catch {
- return [];
- }
-}
-
-interface PixabayPhoto {
- id: number;
- imageWidth: number;
- imageHeight: number;
- user: string;
- tags: string;
- webformatURL: string;
- largeImageURL: string;
-}
-
-async function fetchPixabay(query: string, page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
- const url = `https://pixabay.com/api/?key=${env.pixabay.apiKey}&q=${encodeURIComponent(query)}&page=${page}&per_page=${perPage}&orientation=horizontal&image_type=photo`;
- try {
- const res = await fetch(url);
- if (!res.ok) return [];
- const data = await res.json();
- const results: PixabayPhoto[] = data.hits ?? [];
- return results.map((photo) => ({
- id: `pixabay-${photo.id}`,
- urls: {
- regular: photo.largeImageURL,
- small: photo.webformatURL,
- },
- alt: photo.tags,
- photographer: photo.user,
- color: "#1a1a1a",
- width: photo.imageWidth,
- height: photo.imageHeight,
- }));
- } catch {
- return [];
- }
-}
-
-// Discovery mode - curated/random photos
-async function fetchUnsplashCurated(page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
- const queries = [
- "blur gradient", "mesh gradient", "dark minimal wallpaper", "neon city night",
- "abstract wave dark", "geometric dark background",
- "deep space stars",
- "aurora sky", "minimal texture dark",
- ];
- const query = queries[Math.floor(Math.random() * queries.length)];
- return fetchUnsplash(query, page, perPage);
-}
-
-async function fetchPexelsCurated(page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
- const url = `https://api.pexels.com/v1/curated?page=${page}&per_page=${perPage}`;
+async function callApi(params: URLSearchParams): Promise<UnifiedPhoto[]> {
try {
- const res = await fetch(url, {
- headers: { Authorization: env.pexels.apiKey },
- });
+ const res = await fetch(`/api/photos?${params.toString()}`);
if (!res.ok) return [];
- const data = await res.json();
- const results: PexelsPhoto[] = data.photos ?? [];
- return results
- .filter((photo) => photo.width >= photo.height)
- .map((photo) => ({
- id: `pexels-${photo.id}`,
- urls: {
- regular: photo.src.large,
- small: photo.src.medium,
- },
- alt: photo.alt || "",
- photographer: photo.photographer,
- color: photo.avg_color,
- width: photo.width,
- height: photo.height,
- }));
+ const data = (await res.json()) as { photos?: UnifiedPhoto[] };
+ return data.photos ?? [];
} catch {
return [];
}
}
-async function fetchPixabayCurated(page = 1, perPage = 20): Promise<UnifiedPhoto[]> {
- const queries = ["blur gradient", "dark minimal", "city dark", "blurred", "night sky", "minimalist background", "wallpaper sky"];
- const query = queries[Math.floor(Math.random() * queries.length)];
- return fetchPixabay(query, page, perPage);
-}
-
-const discoveryCache: { photos: UnifiedPhoto[]; timestamp: number } = {
- photos: [],
- timestamp: 0,
-};
-const DISCOVERY_TTL = 5 * 60 * 1000;
-
export async function fetchPhotos(
query: string,
page = 1,
perPage = 20
): Promise<UnifiedPhoto[]> {
- const provider = getNextProvider();
-
- switch (provider) {
- case "unsplash":
- return fetchUnsplash(query, page, perPage);
- case "pexels":
- return fetchPexels(query, page, perPage);
- case "pixabay":
- return fetchPixabay(query, page, perPage);
- default:
- return [];
- }
+ const params = new URLSearchParams({
+ mode: "search",
+ q: query,
+ page: String(page),
+ perPage: String(perPage),
+ });
+ return callApi(params);
}
export async function fetchDiscoveryPhotos(): Promise<UnifiedPhoto[]> {
- if (
- discoveryCache.photos.length > 0 &&
- Date.now() - discoveryCache.timestamp < DISCOVERY_TTL
- ) {
- return [...discoveryCache.photos].sort(() => Math.random() - 0.5);
- }
-
- const [unsplashPhotos, pexelsPhotos, pixabayPhotos] = await Promise.all([
- fetchUnsplashCurated(1, 7).catch(() => []),
- fetchPexelsCurated(1, 7).catch(() => []),
- fetchPixabayCurated(1, 6).catch(() => []),
- ]);
-
- const allPhotos = [...unsplashPhotos, ...pexelsPhotos, ...pixabayPhotos];
- const shuffled = allPhotos.sort(() => Math.random() - 0.5);
-
- discoveryCache.photos = shuffled;
- discoveryCache.timestamp = Date.now();
-
- return shuffled;
+ const params = new URLSearchParams({ mode: "discovery" });
+ return callApi(params);
}
const searchCache = new Map<string, { photos: UnifiedPhoto[]; timestamp: number }>();
diff --git a/proxy.ts b/proxy.ts
index 61e9c34..0f7d508 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -1,4 +1,3 @@
-import { updateSession } from "@/utils/supabase/middleware";
import { type NextRequest } from "next/server";
import createIntlMiddleware from 'next-intl/middleware';
import { locales, defaultLocale } from './i18n';
@@ -16,11 +15,6 @@ export default async function proxy(request: NextRequest) {
const intlResponse = intlMiddleware(request);
intlResponse.headers.set('x-user-country', country);
- const supabaseResponse = await updateSession(request);
- supabaseResponse.cookies.getAll().forEach((cookie) => {
- intlResponse.cookies.set(cookie.name, cookie.value);
- });
-
return intlResponse;
}