Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

252
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda