2

I want to use react components as pages, and I want them to be rendered through express routes.

So basically I am trying to do SSR with just express and react.

package.json:

{
    "name": "project",
    "version": "1.0.0",
    "main": "index.js",
    "description": "",
    "scripts": {
        "dev": "nodemon index.js"
    },
    "keywords": [],
    "author": "",
    "license": "MIT",
    "type": "module",
    "dependencies": {
        "express": "^4.18.1",
        "nodemon": "^2.0.19",
        "react": "^18.2.0",
        "react-dom": "^18.2.0"
    }
}

index.js:

import express from "express";
import React from "react";
import ReactDOMServer from "react-dom/server";
import Home from "./Home";

const app = express();
const port = 3000;

app.get("/", (req, res) => {
    res.send(ReactDOMServer.renderToString(<Home />));
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});

Home.js:

export default function Home() {
    return (
        <div>
            <h1>home</h1>
            <p>hello world</p>
        </div>
    );
}

When I run npm run dev, I get this error:

res.send(ReactDOMServer.renderToString(<Home />));
SyntaxError: Unexpected token '<'

I figured it was from the JSX stuff, so I tried installing some babel packages, and updating my dev script:

{
    "name": "project",
    "version": "1.0.0",
    "main": "index.js",
    "description": "",
    "scripts": {
        "dev": "nodemon index.js --exec babel-node --presets env,react"
    },
    "keywords": [],
    "author": "",
    "license": "MIT",
    "type": "module",
    "dependencies": {
        "@babel/node": "^7.18.6",
        "@babel/preset-env": "^7.18.6",
        "@babel/preset-react": "^7.18.6",
        "express": "^4.18.1",
        "nodemon": "^2.0.19",
        "react": "^18.2.0",
        "react-dom": "^18.2.0"
    }
}

But the error still occurs when I do npm run dev.

How do I simply get express to render a react component when a certain route is visited? I prefer doing it this way since I will have API routes as well, so I don't want to fragment the routing into a mixture of express and react router, etc.

jaxramus
  • 145
  • 2
  • 6
  • 1
    You should try NextJS. – Kaneki21 Jul 14 '22 at 18:56
  • 1
    @Kaneki21 i've tried nextjs. i want delcarative routing. i want to create a very simple monolithic framework that uses express for backend and react for frontend. its amazing just how complicated this simple task is for me. – jaxramus Jul 14 '22 at 19:09
  • Also relevant: [SSR with React : Unexpected token '<' in call to renderToString()](https://stackoverflow.com/questions/68716822/ssr-with-react-unexpected-token-in-call-to-rendertostring) and [this medium post](https://codeburst.io/react-server-side-rendering-ssr-with-express-and-css-modules-722ef0cc8fa0) – ggorlen Jul 15 '22 at 01:31

0 Answers0