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

105
Views
How do I load mapbox in Next.js?

I'm using Next.js and their next/script component to load mapbox in a <Map /> component. This seems to work.

Map.js

import Script from 'next/script';

export default Map() {

  const createMap = () => {
    // set access token
    mapboxgl.accessToken = 'xxxxxxxxxxxxxxx...';

    // create map
    const map = new mapboxgl.Map({...});
  }

  return (
    <>
      <Script
        onLoad={() => {
          createMap();
        }}
        src="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js"
      />
      <div id="map"></div>
    </>
  );
}

1 - If I have multiple instances of <Map /> on a page, will Next.js load this script multiple times?

Is there a better way to load this script once, globally and synchronously? It doesn't seem to work if I load it in my _document.js page. Or is this not an issue?

2 - I also have to load the CSS file. Right now I have it loaded on the page that has the map on it.

pages/contact.js

import Head from 'next/head';

export default function PageContact() {
  return (
    <Head>
      <link href="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css" rel="stylesheet" />
    </Head>
  );
}

If I add maps to other pages, I'd have to include this CSS file on all those other pages, resulting in a lot of duplication. Should I abstract this <Head> to its own component and include that on each page?

Or should I be moving this <Head> component into the <Map> component? It makes sense to centralize this style in one place, but at that point, just like the <Script>, I'm guessing Next.js would load the CSS file each time the component is instantiated, so if a page had more than one map on it, the CSS would be loaded multiple times.

What is the best way to load Mapbox in a Next.js project?

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!