How to dynamically insert scripts into nuxt2 body?

16 Views Asked by At

there is such a method

export const fetchSettings = async (axios, lang) => {     try {         const response = await axios.$post('/api/settings/all', {lang})         return response.data     } catch (error) {         return {             success: false,             error: error.response ? error.response.data : 'Server error',         }     } }

it gets all the global data for the application which is filled in in the admin panel and there are 2 keys body_script and head_script in which scripts for Google Analytics, etc. are transmitted in default format

<!-- Google tag (gtag.js) --\>

window.dataLayer = window.dataLayer || \[\];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', ',blablabla');

so you need to somehow insert them into the dom and for it to work, that is, as far as I understand, you need to do this on the server side the option with head() is suitable for head_script, this is what I did. All that remains is to insert the body_script scripts at the end of the body I tried to use serverMiddleware, but in the end I didn’t really understand how to do it, since I had no experience with serverMiddleware how can I do this please tell me, thanks in advance

I tried the option with mounted

mounted() { 
        const settings = this.$store.getters['app_settings/getSettings'] || {}
        if (!settings) return
        document.body.insertAdjacentHTML('beforeend', settings); },
    }

I also tried this option, but I have no experience with serverMiddleware and it didn’t work out, since I don’t really understand how to work with serverMiddleware

import { fetchSettings } from '../services/adminSettingService.js';

export default async function (req, res, next) {
try {
console.log('Server middleware executed');
const settings = await fetchSettings(req.$axios, req.headers.lang);
console.log(settings.success);

    if (settings.success && settings.data && settings.data.bodyScripts) {
      const bodyScripts = settings.data.bodyScripts;
      bodyScripts.forEach(script => {
        res.write(`<script>${script}</script>`);
      });
    }
    res.end(); 
    
    next(); 

} catch (error) {
console.error('Error fetching and inserting body scripts:', error);
next(error);
}
}

in this example console.log did not work for me and I did not understand why

0

There are 0 best solutions below