Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

347
Views
How to pass a variable from nextjs to a vanilla js file?

for Canvas Dom operations I included a Vanilla JS file with 'next/script' into my NextJs file. <Script id="canvasJS" src="/lib/canvas.js" ></Script> That works fine so far. Now I need to pass a variable like an ID from the NextJs file to the Vanilla File. For onClick it works fine with ()=>functionName(value), but I have no idea how to pass a value without a user interaction.

It would be cool if someone could tell me how to do that.

thanks in advance Frank

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The easiest approach is to read window.__NEXT_DATA__.props.pageProps on your vanilla js script. The object is the hydrated props that are coming from server and will be passed to your page component.

But if i were you i will use something like this.

import { useLayoutEffect } from 'React';
import Script from 'next/script';

export default function Component() {

  useLayoutEffect(() => {
   // do something you want to do with variable and external script
  },[]);

  return (
    <>
      <Script src="/lib/canvas.js"/>
    </>
  )
}

Not entirely sure about what is canvas.js does. Probably you could use something like this. The useLayoutEffect will run on the browser after DOM mutation, so the code inside useLayoutEffect will run after the script is loaded.

For more detail about next/script you can read this docs page. https://nextjs.org/docs/basic-features/script

about 4 years ago · Juan Pablo Isaza Report

0

Ok, my way to do it, is to use local storage.

In my case I check the URL for a board ID in a getServerSideProps(ctx) function and if no ID is set I create a unique one.

Then I return the props. In the client side function I pick the bid from the props and write it to local storage:

Next.js

if (typeof window !== "undefined") 
{
  localStorage.setItem('bid', bid) ;  
}

Then in the vanilla JS file I grab the ID by

Vanilla JS

const bid = localStorage.getItem('bid');
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!