inject `<script>` in rendered HTML when `ssr: false`
See original GitHub issueEnvironment
Nuxt project info: 11:29:52
- Operating System:
Darwin
- Node Version:
v14.18.1
- Nuxt Version:
3.0.0-rc.1
- Package Manager:
npm@6.14.15
- Builder:
vite
- User Config:
typescript
,modules
,ssr
,app
,css
,vite
- Runtime Modules:
@pinia/nuxt@0.1.9
- Build Modules:
-
Reproduction
https://stackblitz.com/edit/github-ztv7ch-3v2mxy?file=nuxt.config.ts
Describe the bug
As described here: https://github.com/nuxt/framework/discussions/5476. I need to inject a script in the <head>
tag, to be able to set some runtime configuration on the global window
object.
I’m injecting the script using the nuxt.config.ts
:
export default defineNuxtConfig({
ssr: false,
typescript: {
shim: false,
},
modules: ["@pinia/nuxt"],
app: {
head: {
link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }],
script: [
{
// injects the config based on the environment
src: "/static/config/config.js",
},
],
},
},
vite: {
plugins: [svgLoader()],
},
});
config.js
:
window.config = {
ENV: "dev",
API: {
EXPERIENCE_RAW_SERVICE_BASE_URL: "https://experience-raw-service.dev.company.com",
},
};
The new meta module injects this script at runtime (as you can see, there is no <script>
tag in the html output):
<!DOCTYPE html>
<html >
<head >
<link rel="stylesheet" href="/_nuxt/entry.983043ac.css">
</head>
<body >
<div id="__nuxt"></div><script>window.__NUXT__={serverRendered:false,config:{public:{},app:{baseURL:"\u002F",buildAssetsDir:"\u002F_nuxt\u002F",cdnURL:""}}}</script><script type="module" src="/_nuxt/entry-3549318c.mjs"></script>
</body>
</html>
The problem is that this script should be executed before anything else. But as you can see in the repro project, if I’m trying to access window.config
in a Plugin, I get undefined
.
This is because some of the application code is run before the config.js
script is injected in the <head>
.
There should be a way to run this script before anything else in the page.
Note: This issue is related to “client side only” projects (ssr: false
), setting ssr: true
solves this issue.
Additional context
No response
Logs
No response
Issue Analytics
- State:
- Created a year ago
- Reactions:8
- Comments:5 (4 by maintainers)
Top GitHub Comments
Using the new
render:html
hook (https://github.com/nuxt/framework/issues/6571), it is now easily possible to inject some scripts universally:Sandbox: https://stackblitz.com/edit/github-86cqr7-vvdzwx?file=server%2Fplugins%2Frender.ts,app.vue,public%2Fconfig.js,nuxt.config.ts
Let’s keep it open until introduce tag utils for a complete solution for #5553.