'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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source