์์ธํ์ด์ง์์ ๋ฉํ๋ฐ์ดํฐ๋ฅผ ์ถ๊ฐํ๋ ๊ณผ์ ์์ ๋ผ์ฐํฐ ํธ๋ค๋ฌ๋ก ๋ง๋ api๋ฅผ ์ฌ์ฉํด์ผ ํด์ api๋ฅผ ํธ์ถํ์๋๋ฐ, Next.js ์๋ฒ ์ปดํฌ๋ํธ(page.tsx, generateMetadata)์์ API ํธ์ถ ์ "Failed to parse URL" ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. ํด๋ผ์ด์ธํธ ์ปดํฌ๋ํธ์์๋ ์ ์๋ํ๋ API ํธ์ถ ํจ์๊ฐ ์๋ฒ ์ปดํฌ๋ํธ์์๋ ๋์ํ์ง ์์์ต๋๋ค.
// utils/api/hospitalDetail.ts
const hospitalDetail = async (id: string) => {
try {
const res = await fetch(`/api/hospitalDetail?id=${id}`);
if (!res.ok) {
throw new Error('Failed to fetch hospital detail');
}
const data = await res.json();
return data;
} catch (error) {
console.error('Error fetching hospital details:', error);
throw error;
}
};
// app/hospital/[...id]/page.tsx
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const id = params?.id[0];
try {
// ์ฌ๊ธฐ์ ์ค๋ฅ ๋ฐ์: Failed to parse URL
const detailData = await hospitalDetail(id);
return {
title: detailData.dutyName,
description: detailData.dutyAddr,
};
} catch (error) {
console.error('Error:', error);
return { title: '๋ณ์ ์ ๋ณด' };
}
}
์ด ๋ฌธ์ ๋ Next.js์ ์๋ฒ ์ปดํฌ๋ํธ์ ํด๋ผ์ด์ธํธ ์ปดํฌ๋ํธ์ ์คํ ํ๊ฒฝ ์ฐจ์ด ๋๋ฌธ์ ๋ฐ์ํ์ต๋๋ค:
/api/...)๊ฐ ํ์ฌ ๋ธ๋ผ์ฐ์ ์ URL์ ๊ธฐ์ค์ผ๋ก ์ฌ๋ฐ๋ฅด๊ฒ ํด์๋ฉ๋๋ค.์คํ ํ๊ฒฝ์ ๊ฐ์งํ์ฌ ์ ์ ํ URL์ ์์ฑํ๋ ์ ํธ๋ฆฌํฐ ํจ์๋ฅผ ๊ตฌํํ์ต๋๋ค:
// utils/api/hospitalDetail.ts
export const getHospitalApiUrl = (id: string) => {
// ๋ธ๋ผ์ฐ์ ์์ ์คํ ์ค์ธ์ง ํ์ธ
const isClient = typeof window !== 'undefined';
if (isClient) {
// ํด๋ผ์ด์ธํธ์์๋ API ๋ผ์ฐํฐ ์ฌ์ฉ
return `/api/hospitalDetail?id=${id}`;
} else {
// ์๋ฒ์์๋ ์ ๋ URL ์ฌ์ฉ
const baseUrl = process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: 'http://localhost:3000';
return `${baseUrl}/api/hospitalDetail?id=${id}`;
}
};
const hospitalDetail = async (id: string) => {
try {
const apiUrl = getHospitalApiUrl(id);
const res = await fetch(apiUrl);
if (!res.ok) {
throw new Error('Failed to fetch hospital detail');
}
const data = await res.json();
const detailData = data.data[0];
return detailData;
} catch (error) {
console.error('Error fetching hospital details:', error);
throw error;
}
};
typeof window !== 'undefined'๋ฅผ ์ฌ์ฉํด์ ํด๋ผ์ด์ธํธ ์ฌ์ด๋์ธ์ง ์๋ฒ ์ฌ์ด๋์ธ์ง ํ์ธ๐ ๋ฐฐ์ด ์
1. Next.js์ ์๋ฒ ์ปดํฌ๋ํธ์ ํด๋ผ์ด์ธํธ ์ปดํฌ๋ํธ์ ์คํ ํ๊ฒฝ ์ฐจ์ด๋ฅผ ์ดํด
2. typeof window๋ฅผ ํ์ฉํ ํ๊ฒฝ ๊ฐ์ง ๊ธฐ๋ฒ
3. ์๋ฒ์ ํด๋ผ์ด์ธํธ์์์ URL ํด์ ์ฐจ์ด๋ฅผ ์ดํด
๐ ๊ฐ์ ๋ ์
1. ์๋ฒ์ ํด๋ผ์ด์ธํธ ์ปดํฌ๋ํธ์์ ๋์ผํ API ํจ์๋ฅผ ์ฌ์ฉ
2. API ํธ์ถ ๋ก์ง์ ํ ๊ณณ์์ ๊ด๋ฆฌ
3. ํ๊ฒฝ ๋ณ์๋ฅผ ํ์ฉ