Next.jsのServer ActionsでCloud Tasksを呼び出したときにエラーになったのでメモ。
具体的には以下のような感じでCloud Tasksを呼び出すとエラーになってしまった。
import { CloudTasksClient } from "@google-cloud/tasks";
export default function Home() {
const handle = async () => {
"use server";
const client = new CloudTasksClient();
await client.createTask({
parent: queueName,
task: {
httpRequest: {
// ...(snip)...
},
},
});
}
return (
<button onClick={handle}>Click Me</button>
);
}
発生したエラーは以下の通り
Cannot find module '/path/to/my-app/node_modules/@google-cloud/tasks/build/esm/src/v2/cloud_tasks_client_config.json'
webpackでビルドされるとき cloud_tasks_client_config.json が読み取れなくなっているのが原因のようなので、以下のような感じで next.config.ts の serverExternalPackages に指定することで、バンドル対象から除外されてnode_modules配下のファイルを読み込んでくれるみたいです。
{
serverExternalPackages: ["@google-cloud/tasks"],
}
https://nextjs.org/docs/app/api-reference/config/next-config-js/serverExternalPackages
ちなみに aertje/cloud-tasks-emulator で @grpc/grpc-js を使っている場合、同様の理由で
[TypeError: Channel credentials must be a ChannelCredentials object]
というエラーが発生するので、こちらも追加すればOK
{
serverExternalPackages: ["@google-cloud/tasks", "@grpc/grpc-js"],
}