How to dynamically generate and implement JSON-LD structured data in Next.js?

I’m building a Next.js application and need to implement JSON-LD structured data dynamically for SEO purposes. My goal is to generate schema markup for different page types (e.g., blog posts, product pages, and services).

Here’s my approach so far:

I’m using getServerSideProps to fetch data.
I’m injecting JSON-LD into the tag inside from next/head.