Skip to content

Instantly share code, notes, and snippets.

@manabuyasuda
Created August 20, 2025 08:46
Show Gist options
  • Save manabuyasuda/eb4cde57e4bfa4db6b27594ffc146aa8 to your computer and use it in GitHub Desktop.
Save manabuyasuda/eb4cde57e4bfa4db6b27594ffc146aa8 to your computer and use it in GitHub Desktop.
canonicalなどに使用するURLを組み立てるヘルパー関数
/**
* パスを配列で渡して絶対URLを安全に構築する
* 環境変数からベースURLを取得し、URL()コンストラクターを使用してURLエンコーディングと妥当性検証をする
* パスの先頭・末尾のスラッシュは自動的に正規化される
*/
export function buildAbsoluteUrl(pathSegments: string[]): string | null {
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL;
if (!baseUrl) return null;
try {
// パスを正規化して空文字列を除外
const cleanPaths = pathSegments
.map(path => {
// 空文字列はスキップ
if (path === '') return '';
// 先頭と末尾のスラッシュを削除
return path.replace(/^\/+|\/+$/g, '');
})
.filter(path => path !== ''); // 空文字列を全て除外
// URLパスを構築
const fullPath = cleanPaths.join('/');
// URL()コンストラクターを使用して安全にURLを構築
const url = new URL(fullPath, baseUrl);
return url.toString();
} catch (error) {
// URLが不正な場合は上位でハンドリングできるようにエラーを再スロー
throw new Error(
`Invalid URL construction: baseUrl=${baseUrl}, pathSegments=${JSON.stringify(pathSegments)}`,
{
cause: error,
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment