How to Pass Data from Express Server with NextJS to a Page?

Solution for How to Pass Data from Express Server with NextJS to a Page?
is Given Below:

I have an ExpressJS server with NextJS like shown in the example here. There are some pages that I want to server render from my express server.

I came up with the solution below:

// server.js

const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express()

  server.get('/server-rendered', (req, res) => {
    // get data from database
    return app.render(req, res, '/server-rendered', { ...req.query, dbData })
  })

  server.all('*', (req, res) => handle(req, res))

  server.listen(3000)
})
// pages/server-rendered.js

const ServerRenderedPage = ({ dbData }) => (
    <div>
        {JSON.stringify(dbData, null, 4)}
    </div>
)

export const getServerSideProps = (context) => ({
    props: {
        dbData: context.query.dbData
    }
})

export default ServerRenderedPage

The solution above works fine. However, I noticed that in production, when the page is server rendered, the HTML contains a script with the id __NEXT_DATA__ (to hydrate the page), but it contains the dbData both in pageProps and in query (see below):

<script id="__NEXT_DATA__" type="application/json">
    {
        "props": {
            "pageProps": {
                "dbData": {}
            }
        },
        "query": {
            "dbData": {}
        },
        // ...
    }
</script>

So if I pass a big amount of data from my express server, the page will load slower since its size will be way larger that it needs to be, since there is duplicate data in the __NEXT_DATA__ script tag.

Does anyone have a better solution for how to pass data from custom NextJS server to a page?

I am aware that I can fetch data in getServerSideProps, but that is slower than directly rendering a page from a custom NextJS server.

So I came up with a solution for how to pass data from an Express NextJS server to a NextJS page without the data being outputted twice in the HTML.

// server.js

server.get('/server-rendered', async (req, res) => {
    // get data from database
    res.dbData = await db.query()

    return app.render(req, res, '/server-rendered', req.query)
})
// pages/server-rendered.js

export const getServerSideProps = ({ res }) => ({
    props: {
        dbData: res.dbData
    }
})

Alternatively, you can fetch data from the database directly inside getServerSideProps as @juliomalves suggested, as shown below.

// pages/server-rendered.js

export const getServerSideProps = async context => {
    // get data from database
    const dbData = await db.query()

    return {
        props: {
            dbData
        }
    }
}