2

I am trying React18 + express to make my react as server rendered application.

I have created a very simple express server that is supposed to send an HTML code to the browser.

import express from "express"
import React from "react"
import { renderToPipeableStream } from "react-dom/server"

const app = express()

app.get("/", (req, res) => {
  const { pipe } = renderToPipeableStream(<h1>Hello World</h1>, {
    onShellReady() {
      res.setHeader("content-type", "text/html")
      pipe(res)
    },
  })
})

app.listen(3000, () => {
  console.log("RUNNING..")
})

The Hello World doesn't get printed and i am stuck with this error -

const { pipe } = renderToPipeableStream(<h1>Hello World</h1>, {
                                          ^

SyntaxError: Unexpected token '<'
    at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)
    at async link (node:internal/modules/esm/module_job:64:21)

However, when i send a plain string as "Hello World" it does rendered on the browser at the given PORT.

Why it cannot send a simple h1 tag as an HTML?

anshul
  • 661
  • 9
  • 27
  • Because `

    ` is only understood within the context of `document` and node doesn't understand what that is. You'll likely have to transpile any JSX using Babel, or [just use `React.createElement`](https://remarkablemark.medium.com/server-side-rendering-with-react-46715f501651) instead.

    – Andy Jul 02 '23 at 11:21
  • @Andy but this is not JSX, rather a simple h1 tag? – anshul Jul 02 '23 at 11:26
  • Then why is it not quoted? I think you are mixing JSX with Javascript and HTML. – Grzegorz W Jul 02 '23 at 11:27
  • @GrzegorzW well why it would be quoted? If i do like this "

    hello world

    ", the h1 tag gets rendered as well (obviously). I do not understand, what transpilation do i need for an HTML h1 tag?
    – anshul Jul 02 '23 at 11:31
  • There is not such thing as "h1 tag" in Javascript. And you are trying to run a Javascript code. So either this has to be a string or you have to run a pre-processing on the file (aka transpilation) so that you get an output that is a valid javascript. I think if you would share your project/folder structure and a command you try to run this with it would be easier to explain or confirm. – Grzegorz W Jul 02 '23 at 11:38
  • @GrzegorzW Oh right! I created a minimal repo here - https://github.com/abhinav-anshul/react18-server The goal here is to create a react18 app and bundle it using parcel. then make it server side rendered using express by opening a port on 3000. Very thanks :) – anshul Jul 02 '23 at 11:45

0 Answers0