renderPage()

Environment: Node.js.

We use renderPage() to server-side render a page:

// server.js
// Environment: Node.js server

// In this example we use Express.js but we could use any other server framework
import express from 'express'
import { renderPage } from 'vite-plugin-ssr'

const isProduction = process.env.NODE_ENV === 'production'
const root = `${__dirname}/..`

startServer()

async function startServer() {
  const app = express()

  if (isProduction) {
    app.use(express.static(`${root}/${outDir}/client`))
  } else {
    const vite = await import('vite')
    viteDevMiddleware = (await vite.createServer({
      root,
      server: { middlewareMode: 'ssr' }
    })).middlewares
    app.use(viteDevMiddleware)
  }

  app.get('*', async (req, res, next) => {
    const url = req.originalUrl
    const pageContextInit = { url }
    const pageContext = await renderPage(pageContextInit)
    if (!pageContext.httpResponse) return next()
    const { body, statusCode, contentType } = pageContext.httpResponse
    res.status(statusCode).type(contentType).send(body)
  })

  const port = 3000
  app.listen(port)
  console.log(`Server running at http://localhost:${port}`)
}
  • pageContext.httpResponse is null when a) an error occurred while rendering _error.page.js, or b) we didn't define the page _error.page.js and and an error occured.
  • pageContext.httpResponse.statusCode is either 200, 404, or 500.
  • pageContext.httpResponse.contentType is either text/html or application/json. (The Content-Type is application/json when Client Routing fetches the pageContext of the newly navigated page.)
  • pageContext.httpResponse.body is the HTML string returned by the render() hook with additional <script> and <style> tags automatically injected by vite-plugin-ssr.

renderPage() is framework agnostic: we can use vite-plugin-ssr with any server framework (Koa, Hapi, Fastify, vanilla Node.js, ...) and any deploy environment (AWS, Cloudflare Workers, Vercel, ...).

Examples: