DEV Community

Cover image for Adding Alexa script in NUXT SSR.
Mahinul Islam Meem
Mahinul Islam Meem

Posted on

Adding Alexa script in NUXT SSR.

Adding static scripts for various reasons in nuxt server side applications sometimes is not easy because there no html files here. So what to do then?
I had faced this problem while adding alexa certified scripts and google ad manager scripts to my project. As I didn't find any module to integrate Amazon Alexa to nuxt project. So I have found these two options.

1. Adding script to nuxt.config.js

In the head section of the config file you can easily add scripts. But some static scripts might cause problems for that you have add to this to head __dangerouslyDisableSanitizers: ['script'] so that nuxt doesn't sanitize your scripts.

export default {
  // Global page headers (https://go.nuxtjs.dev/config-head)
  head: {
    __dangerouslyDisableSanitizers: ['script'],
    titleTemplate: (title) => {
      return title ? `${title} - News` : 'News'
    },
    title: '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ],
    script: [
      {
        src: 'https://securepubads.g.doubleclick.net/tag/js/gpt.js',
        async: true
      },
      {
        type: 'text/javascript',
        hid: 'alexa',
        innerHTML: `
        _atrk_opts = { atrk_acct: "hXXXXXXXXX", domain: "XXXXXXX.com", dynamic: true };
        (function() { var as = document.createElement('script'); as.type = 'text/javascript'; as.async = true; as.src = "https://certify-js.alexametrics.com/atrk.js"; var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(as, s); })();
        `
      }
   ]
 }
}
Enter fullscreen mode Exit fullscreen mode

You can also add scripts on specific pages or components by adding scripts in this way to the head section of the vue file.

2. Adding script to app.html

In nuxt.js you can create a app.html file inside which is an actual HTML frame of nuxt document and add scripts to it. You can see detailed documentation from this link: https://nuxtjs.org/docs/2.x/concepts/views#app-template

<!DOCTYPE html>
<html {{ HTML_ATTRS }}>
  <head>
    {{ HEAD }}
  </head>
  <body {{ BODY_ATTRS }}>
    {{ APP }}
  </body>
  <script type="text/javascript" src="https://securepubads.g.doubleclick.net/tag/js/gpt.js" async></script>
</html>
Enter fullscreen mode Exit fullscreen mode

I am using the nuxt 2.14.6 version for this project.

These are the ways I have tried. If you find more efficient solution please do share here. Thank you and happy coding.

Discussion (2)

Collapse
cannap profile image
Marko Bolliger

you can also say body:true in script then it will be added before

Collapse
pixsaoj profile image
Pixsa

Is there a way to put store variables inside app.html?