1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Next.js】referenceerror: await is not defined next cloudflareの解決方法

Posted at

はじめに

本記事では、Next.jsCloudflare Pagesを利用する際に発生したエラーと、その解決方法について紹介します。

この記事は、個人的なアウトプットを目的として作成しています。内容には誤りや不足が含まれている可能性がありますので、もしお気づきの点がありましたら、ご指摘いただけますと幸いです。

現象

npm run devを実行したところ、next.config.ts内で以下のようなエラーが発生しました。

await (0, _nextdev.setupDevPlatform)();
    ^
ReferenceError: await is not defined

原因

このエラーの原因は、next.config.tsCommonJS モジュールとして解釈されるため、トップレベルで awaitを使用できない点にあります。

以下のような記述が原因でエラーになります:

next.config.ts
import type { NextConfig } from "next";
import { setupDevPlatform } from "@cloudflare/next-on-pages/next-dev";

const nextConfig: NextConfig = {
  /* config options here */
};

if (process.env.NODE_ENV === "development") {
  await setupDevPlatform(); 
}

export default nextConfig;

解決方法

ファイルの拡張子を.tsから.mjsに変更することで、ESM(ECMAScript Modules)として扱われ、トップレベルで await を使用できるようになります。

next.config.mjsに変更し、型アノテーション(TypeScript特有の記法)も削除します:

next.config.mjs
import { setupDevPlatform } from "@cloudflare/next-on-pages/next-dev";

const nextConfig = {
  /* config options here */
};

if (process.env.NODE_ENV === "development") {
  await setupDevPlatform();
}

export default nextConfig;

終わりに

Cloudflare PagesNext.jsを組み合わせて開発を行う際、ローカル開発用の設定でESMの構文が必要になることがあるようです。

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?