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

256
Views
How to add global scripts to a NextJS website, but requires data fetching first?

I need to add <script> tags that applies to each page on my NextJS website. But first, I need to create a POST request to an API to get the data that will be used for the src attribute of these <script> tags.

I need to create the POST request in server-side because the request requires secret keys, so creating the POST request in _app.tsx is removed from my choices.

That leaves me with _document.tsx, which I am not sure how it should be implemented. This is what I have so far:

const getSessionTags = async () => {...};

export default class _Document extends Document {
    static async getInitialProps(ctx: DocumentContext) {
        const initialProps = await Document.getInitialProps(ctx);

        this.sessionTags = await getSessionTags();

        return { ...initialProps, ...getMantineInitialProps };
    }

    render() {
        return (
            <Html>
                <Head></Head>
                <body>
                    <Main />
                    <NextScript />
                    <script async src={`https://website.org/${this.sessionTags.id}`} />
                </body>
            </Html>
        );
    }
}

My current code is nearly similar to the Using _document.js of this article, but it did not show the implementation if you needed to make HTTP requests, only how to embed the <script> tags to _document.tsx

about 4 years ago · Juan Pablo Isaza
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!