🐤
手っ取り早くNext.js(app router)でapiのcorsエラーを回避する方法
前提
下記バージョンでapp routerでの話。
Next.js 13.5.4
問題
Nextでapiリクエストをやってみると下記のようなCORSエラーになる時がある。
Access to fetch at 'http://xxxxxxx' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
解決方法
Route Handlersを使ってサーバー経由でGETリクエストを投げてあげると解消できる。
ざっくり説明すると、CORSはブラウザのセキュリティ機能なので、サーバー側でAPIを叩いてあげればCORSの制限を回避できる。
src/app/api/route.ts
export async function GET() {
const res = await fetch(
`http://xxxxxxx`, // ここにリクエスト先のURLを設定
{ cache: "no-store"}
);
const data: res = await res.json();
return NextResponse.json(data);
}
src/app/api.ts
export const getAllData = async (): Promise<any> => {
const res = await fetch(
`http://localhost:3000/api`,
{ cache: "no-store"}
);
const data = await res.json();
return data;
};
src/app/page.tsx
export default function Home() {
const onClick = async () => {
const data = await getAllData(); // クリックするとlocalhost:3000から、サーバーを経由してhttp://xxxxxのデータを受け取れる
console.log(data);
};
return (
// 省略
)
補足
- CORSについては下記が分かりやすい
- Page routerならAPI Routesっていうので同じことができそう
Discussion