Search code examples
javascriptvue.jsnuxt.jselastic-stackelastic-apm

What is the best way to add APM to NuxtJS project


What is the right way to configure/enable an Elastic APM agent in a Nuxtjs project?

I referred this documentation for a custom NodeJS app. The key takeaway was:

It’s important that the agent is started before you require any other modules in your Node.js application - i.e. before http and before your router etc.

I added the following snippet in nuxt.config.js, but the APM agent is not started or working. I do not see any errors in the app logs.

var apm = require('elastic-apm-node').start({
  serviceName: 'nuxt-app',
  serverUrl: 'http://ELK_APM_SERVER:8200'
})

Is there any other way to do this?


Solution

  • Based on what I've seen it looks like there isn't a "right" way to do this with the stock nuxt command line application. The problem seems to be that while nuxt.config.js is the first time a user has a chance to add some javascript, that the nuxt command line application bootstraps the Node's HTTP frameworks before this config file is required. This means the elastic agent (or any APM agent) doesn't have a chance to hook into the modules.

    The current recommendations from the Nuxt team appears to be

    1. Invoke nuxt manually via -r

           {
             "scripts": {
               "start": "node -r elastic-apm-node node_modules/nuxt/.bin/nuxt"
             }
           }  
      
    2. Skip nuxt and use NuxtJS programmatically as a middleware in your framework of choice

           const { loadNuxt } = require('nuxt')
           const nuxtPromise = loadNuxt('start')
           app.use((req, res) => { nuxtPromise.then(nuxt => nuxt.render(req, res)) })