renderToString “You’re importing a component that imports react-dom/server.”

I was trying to use the renderToString function as some libraries such as leaflet require it to make custom markers. Below is a simple example that recreates the error in a fresh React project:

import { renderToString } from 'react-dom/server';

const html = renderToString(<h2>some content</h2>);


export default function Home() {
  return (
    <main >
      <div >
        <h1>My React App</h1>
      </div>
    </main>
  );
}

Running the code gives the following error:

    ./app/page.js
Error: 
  × You're importing a component that imports react-dom/server. To fix it, render or return the content directly as a Server Component instead for perf and security.
  │ Learn more: https://nextjs.org/docs/getting-started/react-essentials
   ╭─[D:Reactmy-appapppage.js:1:1]
 1 │ import { renderToString } from 'react-dom/server';
   · ──────────────────────────────────────────────────
 2 │ 
 3 │ const html = renderToString(<h2>some content</h2>);
   ╰────

is there anyway to use renderToString?