Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Google analytics doesn't work with NueJS #175

Closed
goblinfactory opened this issue Jan 22, 2024 · 29 comments
Closed

Google analytics doesn't work with NueJS #175

goblinfactory opened this issue Jan 22, 2024 · 29 comments
Assignees
Labels

Comments

@goblinfactory
Copy link
Contributor

goblinfactory commented Jan 22, 2024

I can't find any way to add GA to a NueJS website/blog.

I've tried three approaches

  1. Tried adding it to the <head> element.
  2. Tried adding it at the top of the <main> in a raw <script> tag.
  3. Lastly, I tried following instructions on controlling layout yourself, and defining the entire root layout from <html> as described here : https://nuejs.org/docs/concepts/layout-components.html#root-layout

All three approaches just crash with unexpected token error.
I'm hoping I've done simply obviously wrong.

@nobkd
Copy link
Collaborator

nobkd commented Jan 22, 2024

Is unexpected token error the only thing you get, or is the error more verbose?

If possible, could you also try to provide some (redacted) snippet that represents your GA code?

@nobkd
Copy link
Collaborator

nobkd commented Jan 22, 2024

I searched around and found this example code:

<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'G-XXXXXXX');
</script>

And got this error:

!! parse error layout.html
89 | 
90 | 
91 | // exec('`font-size:${_.size + "px"}`;', data)
92 | export function exec(expr, data={}) {
93 |   const fn = new Function('_', 'return ' + expr)
94 |   const val = fn(data)
     ^
SyntaxError: Unexpected token '.'. Expected a ';' following a class field.
      at <parse> (:5:1)
      at Function (native:1:1)
      at exec (/home/username/.bun/install/global/node_modules/nuejs-core/src/fn.js:94:23)
      at createComponent (/home/username/.bun/install/global/node_modules/nuejs-core/src/render.js:290:25)
      at map (:1:11)
      at /home/username/.bun/install/global/node_modules/nuekit/src/site.js:200:24

Which seems like the code is tried to be parsed as Nue component or something?


Edit:

Yep. I'm sure (at least for me): I added a console.log(expr) in my local installation to the beginning of this function:

export function exec(expr, data={}) {
const fn = new Function('_', 'return ' + expr)
const val = fn(data)
return val == null ? '' : isJS(val) ? val : '' + val
}

And I this when running the dev server:

class Impl { 

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

    gtag('config', 'G-XXXXXXX');
     }

@goblinfactory
Copy link
Contributor Author

goblinfactory commented Jan 22, 2024

@nobkd Txs for that, I was just about to add that. Yes, that's exactly the error I get.
Do you not have Google Analytics installed yourself?
i.e. are we talking about just one problem that my blog has, because you got it working easily, or a problem that we can quickly confirm impacts everyone?

@goblinfactory
Copy link
Contributor Author

Just thinking about it, we might probably be able to quickly hack it by simply moving the second piece of hard coded script into another file and import that as well?

But I dont want to do any further experimenting until I've established whether it works out of the box for anyone else. Otherwise I could be trying to fix a problem that is a side effect of something else.

@goblinfactory
Copy link
Contributor Author

@nobkd Yeah, I tried manually adding it to and Nue just strips it out. Not sure what the render (transform) code in Nue looks like; i assume the blog gets converted to metadata and then rendered; I'm assuming there's no transform to pick up custom GA or script tags and add that to the meta data to make it into the final rendering. Just my initial thoughts.

Here's what I tried;
Screenshot 2024-01-22 at 11 00 29

Both the two lines I added have no impact on any output.

@fritx
Copy link
Collaborator

fritx commented Jan 23, 2024

Actually I ran into problems like this too. Do we have workaround supporting inline <script> and <style> without going into expression parsing errors?

@tipiirai
Copy link
Contributor

This is a bug on the template engine, which treats <script> tags as a special case. Need to fixt this. It's important. Thanks guys.

@tipiirai tipiirai self-assigned this Jan 23, 2024
@tipiirai tipiirai added the bug label Jan 23, 2024
@tipiirai
Copy link
Contributor

Pushed out a new Nue JS/Nuekit versions (0.3.1 and 0.3.2) where this issue is resolved. When a script tag has any attribute, such as type it is passed for the client as is. For example:

<!-- Google Analytics -->
<script type="text/javascript">
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'TAG_ID', 'auto');
  ga('send', 'pageview');
</script>

You can alternatively use a client attribute which passes the script for the client as is and also removes the attribute so that the HTML stays clean. ie.

<script client>
  // hey
</script>

Gets rendered as

<script>
  // hey
</script>

@tipiirai
Copy link
Contributor

Added docs for this.

@goblinfactory
Copy link
Contributor Author

the docs link above is to localhost : actual link to docs is : https://nuejs.org/docs/reference/template-syntax.html#client-side-script-tags

@goblinfactory
Copy link
Contributor Author

@tipiirai
I can't get that to work;
I ran bun install nuekit@latest --global
running nue --version confirms ✓ Nue 0.3.2 • Bun 1.0.22
however, manually running nue build -r blog and then eyeballing the .dist folder, confirms we still have old version .031 see screenshot below

Screenshot 2024-01-23 at 16 38 03

I manually created another starter blog

md upgrade
cd upgrade
bun create nue@latest

I then manually ran a build, nue build
and then did a file compare of the generated files, they look identical

Finally I edited the starter blog template for the brand new getting started nuejs, version 0.32, and added this to the default layout.html

<main>
  <script client>
    alert('hello')
  </script>
  <slot for="content"/>
  <blog-posts :posts/>
</main>

After adding that, and saving. I run nue build and I now get the following errors

 nue build 

✓ Nue 0.3.2 • Bun 1.0.22 
✓ Building site to: ./.dist/dev

✓ Processing styles 4
   home.css
   posts/post.css
   global/global.css
   global/feedback.css

✓ Transpiling components 1
   global/feedback.nue

✓ Generating pages 4
!! parse error layout.html
1 | export default "native";
    ^
SyntaxError: Unexpected string literal 'hello'. Expected a parameter pattern or a ')' in parameter list.
      at <parse> (:4:1)
      at Function (native:1:1)
      at exec (/Users/alanhemmings/.bun/install/global/node_modules/nuejs-core/src/fn.js:94:23)
      at createComponent (/Users/alanhemmings/.bun/install/global/node_modules/nuejs-core/src/render.js:290:25)
      at map (:1:11)
      at /Users/alanhemmings/.bun/install/global/node_modules/nuekit/src/site.js:200:24
      at processTicksAndRejections (:61:39)

   posts/scaleable-design-system.md
!! parse error layout.html
1 | export default "native";
    ^
SyntaxError: Unexpected string literal 'hello'. Expected a parameter pattern or a ')' in parameter list.
      at <parse> (:4:1)
      at Function (native:1:1)
      at exec (/Users/alanhemmings/.bun/install/global/node_modules/nuejs-core/src/fn.js:94:23)
      at createComponent (/Users/alanhemmings/.bun/install/global/node_modules/nuejs-core/src/render.js:290:25)
      at map (:1:11)
      at /Users/alanhemmings/.bun/install/global/node_modules/nuekit/src/site.js:200:24
      at processTicksAndRejections (:61:39)

   posts/color-strategies.md
!! parse error layout.html
1 | export default "native";
    ^
SyntaxError: Unexpected string literal 'hello'. Expected a parameter pattern or a ')' in parameter list.
      at <parse> (:4:1)
      at Function (native:1:1)
      at exec (/Users/alanhemmings/.bun/install/global/node_modules/nuejs-core/src/fn.js:94:23)
      at createComponent (/Users/alanhemmings/.bun/install/global/node_modules/nuejs-core/src/render.js:290:25)
      at map (:1:11)
      at /Users/alanhemmings/.bun/install/global/node_modules/nuekit/src/site.js:200:24
      at processTicksAndRejections (:61:39)

   posts/class-naming-strategies.md
!! parse error layout.html
1 | export default "native";
    ^
SyntaxError: Unexpected string literal 'hello'. Expected a parameter pattern or a ')' in parameter list.
      at <parse> (:4:1)
      at Function (native:1:1)
      at exec (/Users/alanhemmings/.bun/install/global/node_modules/nuejs-core/src/fn.js:94:23)
      at createComponent (/Users/alanhemmings/.bun/install/global/node_modules/nuejs-core/src/render.js:290:25)
      at map (:1:11)
      at /Users/alanhemmings/.bun/install/global/node_modules/nuekit/src/site.js:200:24
      at processTicksAndRejections (:61:39)

   index.md

✓ Copying static files 20
 ... redacted to save space ...
   img/twitter.svg

Time taken: 46ms

➜  upgrade git:(main) ✗ 

@goblinfactory
Copy link
Contributor Author

goblinfactory commented Jan 23, 2024

Is there something else I have to do, to get access to or get started with the @latest ?
I think this ticket should remain open. I'm still able to reproduce the bug, starting from scratch, using steps above, and cannot reproduce the fix.

@nobkd
Copy link
Collaborator

nobkd commented Jan 24, 2024

confirms we still have old version .031 see screenshot below

The version-check wasn't updated in the code: https://github.com/nuejs/nue/blob/master/packages/nuekit/src/init.js#L21-L28


I run nue build and I now get the following errors

That's so weird. For me, it just works... Tested with v0.3.2 and v0.3.3...

@goblinfactory
Copy link
Contributor Author

@nobkd
If I do the following

  1. Create a new empty folder, called test32, cd test32
  2. run nue --version observe you are running 0.3.2, bun, 1.0.22
  3. run nue press enter. (with no parameters)

I now see the following
Screenshot 2024-01-24 at 13 35 33

Questions

  1. Shouldn't .dist/dev/@nue/.031 be /0.32?
  2. If yes, then this explains the bug.
  3. If no, then is are my steps to reproduce in the notes further above correct?

@nobkd
Copy link
Collaborator

nobkd commented Jan 24, 2024

Shouldn't .dist/dev/@nue/.031 be /0.32?

No, because the version check file name has not been updated in the source code. See my last comment: #175 (comment)

It's the same file structure as yours.

Open to see file structure:

image


My commands for a small example:

  • mkdir test32 && cd test32
  • bun create nue@latest
    • Dirname: .
    • Select e.g.: Simple blog
  • sed -i "s/<main>/<main><script client>alert('hello')<\/script>/" layout.html
    • Just to have a simple example <script>
  • nue
  • Open page in browser

image

Open to see command line example:

image

@goblinfactory
Copy link
Contributor Author

goblinfactory commented Jan 24, 2024

@nobkd Your steps are basically the same as mine. But to be extra sure I ran your exact steps, and didn't get an alert, and F12 shows no <script> element.

This could be a bun/package issue;

--- clippy says ---
Screenshot 2024-01-24 at 16 15 55

It sounds like you're encountering an issue where the bun create nue@latest command is not installing the latest version of 'nue'. This could be due to a few reasons:

Cache Issue: Sometimes package managers cache an older version. Try clearing the cache.
Package Publishing Delay: The latest version might not be properly published or recognized by the package registry yet.
Version Tagging Issue: The 'latest' tag might not be correctly assigned to the newest version in the registry.
To troubleshoot:

Check the registry directly (like npmjs.com if 'nue' is an npm package) to see the latest version.
Try installing a specific version instead of using @latest.
Look for any open issues or documentation on 'bun' or 'nue' that might address this problem.


I will investigate further in a few hours. Just in the middle of some work stuff I have to complete first.

Looks like a good excuse to build that Cloudflare CICD build step, which basically will just be something like

npm install bun
bun install nue@latest
nue build -r --production
etc etc ...

Then I can test it on clean build image. If that works, then I just have to ask clippy how to clear my bun caches etc on my dev box. If it doesnt work on a clean build agent, then it could be one of the other problems mentioned by clippy.

@tipiirai tipiirai reopened this Jan 25, 2024
@tipiirai
Copy link
Contributor

Can you check from node_modules that you are using nuejs-core v0.3.1, where this issue was fixed?

@goblinfactory
Copy link
Contributor Author

goblinfactory commented Jan 25, 2024

I'm not using any packages or node modules. I dont have a packages.json file in my project.
I'm only using nue as per the getting started docs, i.e. as a global command line tool, installed globally.
I'm currently checking-in the .dist folder to git, and not using a build step on the cloudflare server so that the deployed site is ACTUALLY the exact site I debug and build locally. (it's a hack, but it works well.)
When I run my fake make script, it calls nue build -r blog --production, then it checks in the built artifacts to git, which then triggers a cloudflare push of content to edge.

I check the version of nue that is being used by calling nue -v, which returns ✓ Nue 0.3.2 • Bun 1.0.22
It might be useful to have nue embed the version of nue in the web headers, and you can later default that to false with an option to include (if people want their dev tools to be private, which I would respect, but for early stage, having this there could be very helpful in situations like this.)

i.e. some bizarre situation where calling from command line nue -v returns version X, but running makefile uses version Y.

@goblinfactory
Copy link
Contributor Author

goblinfactory commented Jan 25, 2024

@tipiirai Actually, here's a simpler demo of the problem.

step 1; add in the script tag to template.html
step 2: run nue build

That's it, that's all you need to do, to see the bug; here's what I get, and you can clearly see the version of nue that is running via the console output, as well as the parsing error unexpected literal string 'hello' we would expect not to see.

Screenshot 2024-01-25 at 11 29 29

@tipiirai
Copy link
Contributor

For some reason you don't have the latest nuejs-core as the dependency, which would fix the above issue. Maybe try bun install on the local install directory.

@goblinfactory
Copy link
Contributor Author

goblinfactory commented Jan 26, 2024

Screenshot 2024-01-26 at 10 39 49 ... then why does Nue report version 0.3.2 when I run build?

I've perhaps misunderstood you. What exactly do you mean by nuejs-core; remember I' m just a user of an executable called Nue, (from my perspective as a new user simply using the tool and following the getting started instructions)
I'm not a team developer, and have no exposure to the innards of the nue architecture. (not yet at least)

@goblinfactory
Copy link
Contributor Author

Using bun package manager and running bun install nue@latest doesnt change anything, see below.
In this screenshot you can see

  1. nue version running
  2. error message
  3. package.json created by bun install nue@latest
Screenshot 2024-01-26 at 11 06 58

@goblinfactory
Copy link
Contributor Author

goblinfactory commented Jan 26, 2024

@tipiirai damn, answer is right there...

bun install nue <-- instead of --> bun install nuekit
Doh!!!
testing now...
p.s. at least I can haz nice async control flow if I wanted! 🤕😆

@goblinfactory
Copy link
Contributor Author

here's the problem I think

  1. I suspect by naming the executable nue and making the name of the tool different from the name of the package
  2. by having --global in your getting started

Now, if at any time in the future, perhaps 3 months from now a user needs a new feature because it's all moved on quite a bit, then lets say 90% of the users look at their command line, and think .. .I need to update "nue"... yknow, that command /utility I keep running.
So they run bun install nue@latest
which it does
now when they run nue, it keeps on using nue from the first gloally installed nuekit package.

Options / suggestions to fix

  1. Change the documentation to NEVER EVER suggest installing it globally. Or this problem will happen for a certain % of users and create a support burden and or lose users
  2. Rebrand the command line tool to Nuejs or nuekit or something, and align the package name exactly with the command line name.
  3. other...? (dunno, to be discussed)

@goblinfactory
Copy link
Contributor Author

@tipiirai
Just finished testing; Sadly running bun install nuekit@latest and using local packages, does not fix the problem. See screenshot. I will test next on clean build machine with Cloudflare build agent.

Screenshot 2024-01-26 at 11 36 26

@goblinfactory
Copy link
Contributor Author

goblinfactory commented Jan 26, 2024

works flawlessly on Cloudflare build agent with bun & npx

@tipiirai here's some more pieces to the puzzle;
I started a new project from scratch, and just like above, it didn't work. But this time I created a new Cloudflare Pages project and used this very complicated build pipeline below

bun update && npx nue build --production

And configured the build output directory in Cloudflare dashboard, and it works flawlessy; ...well, fast and flawlessly! <-- I trademark that!! ...lol

that will be a great tagline, Fast and flawlessly!

I digress, ... so we know it works properly on a clean build machine, and that we have at least 1 person reporting an issue of upgrading to latest packages and dependancies, (me) and for some reason Bun is failing to update.
Here's the proof it's working;
https://fetish-pond-diving.divecode.co.uk/
Screenshot 2024-01-26 at 15 51 53

This spike projects includes a cheesy alert box, just to prove that using <script client> now works.

Below is a redacted extract of the build log from Cloudflare after doing a git push on main branch.

Cloning repository...
[redacted] From [redacted]
[redacted] branch [redacted] -> FETCH_HEAD
HEAD is now at [redacted] update social
Using v2 root directory strategy
Success: Finished cloning repository files
Detected the following tools from environment: bun@1.0.1, nodejs@18.17.1
Installing project dependencies: bun install --frozen-lockfile
bun install v1.0.1 ([redacted])
+ nuekit@0.3.3
15 packages installed
Executing user command: bun install && npx nue build --production
Checked 15 installs across 16 packages (no changes)
bun install v1.0.1 ([redacted])
✓ Nue 0.3.3 • Bun 1.0.1
✓ Building site to: ./.dist/prod
✓ Processing styles 4
✓ Transpiling components 1
✓ Generating pages 4
✓ Copying static files 24
[ images et al]
Time taken: 140ms
Finished
Note: No functions dir at /functions found. Skipping.
Validating asset output directory
Deploying your site to Cloudflare's global network...
Uploading... (41/45)
Uploading... (43/45)
Uploading... (44/45)
Uploading... (45/45)
✨ Success! Uploaded 4 files (41 already uploaded) (0.93 sec)
✨ Upload complete!
Success: Assets published!
Success: Your site was deployed!

The build takes 140ms, and the full site deployment, including CDN cache invalidation takes a further 0.93s (930ms), excluding the time it takes for a git push to actually trigger the build, which in my experience is around 3 to 4seconds. Though that's including the full round trip of how long it takes for the web UI to receive notification, so it's obviously less than that value.

from git push on my local machine, it takes me about 7 seconds, pressing Cmd+R to see the updated site.

@nobkd
Copy link
Collaborator

nobkd commented Jan 28, 2024

Great that it at least works on other devices. +


here's the problem I think

  1. I suspect by naming the executable nue and making the name of the tool different from the name of the package
  2. by having --global in your getting started

I agree, that the command does not fit to the nuekit package. I also some time ago installed nue and then tried to run the nue command, which obviously failed. 😅
And I also dislike the global installation, as the packages are not properly reflected in the project's package list / information.

Change the documentation to NEVER EVER suggest installing it globally. Or this problem will happen for a certain % of users and create a support burden and or lose users
Rebrand the command line tool to Nuejs or nuekit or something, and align the package name exactly with the command line name.

On your side on both points there +


Just finished testing; Sadly running bun install nuekit@latest and using local packages, does not fix the problem

That's just really weird...
Have you tried deleting bun (rm -rf ~/.bun) and local node_modules on your machine and just reinstalling everything? 🤷

Can you share what system you are on? Like operating system (and distribution) or so?


bun update && npx nue build --production

May I ask why you use npx to run nue-command on remote instead of bunx? Or did you just use the one that came to mind first?


And configured the build output directory in Cloudflare dashboard, and it works flawlessy; ...well, fast and flawlessly! <-- I trademark that!! ...lol

lol 😂

@tipiirai
Copy link
Contributor

Awesome work guys! I'm thinking of bundling Nue JS server components inside Nuekit later so that Nue JS only consists of client-side reactive parts. Nue JS is super buggy atm, and I think we should offer React (maybe Svelte) alternatives for building single-page apps. Not that this would solve the Bun install issue here. Just thinking aloud.

@goblinfactory
Copy link
Contributor Author

@tipiirai I have Google Analytics working on my blog using the latest NueJs. closing,
txs for the quick responses.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants