👻

Next.js × Turbopack な環境で New Relic APM の計測をする

に公開

Next.js でアプリケーションをローカルで実行する際には webpack などで実行するのが一般的かと思います。

最近の Next.js では Turbopack というものを利用して実行する方法がありより早く webpack やその他のバンドラーに比べ高速に起動するようです。

Next.js に組み込まれており以下のコマンドだけで実行ができるようになっています。

next dev --turbopack

恥ずかしながらこの記事を書く際に始めてその存在を知りました。
本記事は Turbopack そのものより Turbopack 環境下で New Relic APM を動作させるための記事になりますので詳細については省略します。

シュッと動作環境だけくれという方は以下のリポジトリ参照していただければこれ以上読む必要はありません。
https://github.com/yuzujoe/newrelic-node-examples/tree/add-nextjs-turbopack/nextjs/nextjs-turbopack

以下の記事との差分のみを紹介します。

https://newrelic.com/jp/blog/nerdlog/migrate-nextjs-instrumentation

動作環境

Next.js 15.3.1
Node.js v22.14.0
MacOS 15.2

Next14 では動作ができずもしできた方がいれば是非教えて頂けるとありがたいです🙏

next.config.js の変更

対応としては next.config.js の変更のみで対応ができます。

'use strict'

const nrExternals = require('newrelic/load-externals')

module.exports = {
  experimental: {
    // Without this setting, the Next.js compilation step will routinely
    // try to import files such as `LICENSE` from the `newrelic` module.
    // See https://nextjs.org/docs/app/api-reference/next-config-js/serverComponentsExternalPackages.
    serverComponentsExternalPackages: ['newrelic']
  },

  // In order for newrelic to effectively instrument a Next.js application,
  // the modules that newrelic supports should not be mangled by webpack. Thus,
  // we need to "externalize" all of the modules that newrelic supports.
  webpack: (config) => {
    nrExternals(config)
    return config
  }
}

'use strict'

const nrExternals = require('newrelic/load-externals')

module.exports = {
  //Next15 の場合serverComponentsExternalPackagesからserverExternalPackagesに置き換える
  serverExternalPackages: ['newrelic'],

  //https://nextjs.org/docs/app/api-reference/turbopack#configuration
  torbopack: (config) => {
    nrExternals(config)
    return config
  }
}

この設定でアプリケーションを起動し問題なくデータが転送されていることが確認できていれば成功になります。

内容としては以上になります。

Turbopack サポートの Issue はあるので正式なサポートを期待しつつお役に立てば幸いです。

Discussion