Skip to content

Instantly share code, notes, and snippets.

@twhid
Last active December 17, 2020 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twhid/90dd8844bcc42c35a24c64743abe991c to your computer and use it in GitHub Desktop.
Save twhid/90dd8844bcc42c35a24c64743abe991c to your computer and use it in GitHub Desktop.
minimal typescript/TSX React SSR Express example

minimal typescript/TSX React SSR Express example

To run locally..

ts-node needs to be installed. You'll also need to install express, react, and react-dom.

  1. Make tsConfig.json a sibling to server.tsx
  2. run like so $ NODE_PORT=8888 ts-node server.tsx
  3. open http://localhost:8888/ in a browser.

notes on TS compiler options

"module": "commonjs" import statements need to be compiled to require statements so that Node <=12 can understand them. See ts-node docs re: ESM support.

"jsx": "react" We're running directly in Node after the TS compilation, so we need JS instead of JSX. See TS documentation re: jsx.

"esModuleInterop": true TS compiler will error with this if it's not included: "This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag."

import express, { Request, Response } from 'express';
import React, { FC } from 'react';
import { renderToString } from 'react-dom/server';
const app = express();
const App: FC<{}> = () => {
return (
<html>
<title>Greetings</title>
<body>
<h1>Greetings Earth.</h1>
</body>
</html>
);
};
app.get('*', (_req: Request, res: Response) => {
// note, this is rendering on each request, which for this static app is bad.
// It should be pre-rendered when the app starts.
return res.send(renderToString(<App />));
});
app.listen(process.env.NODE_PORT, () => {
// eslint-disable-next-line no-console
console.log(`Express server app listening on port ${process.env.NODE_PORT}!`);
});
{
"compilerOptions": {
"module": "commonjs",
"jsx": "react",
"esModuleInterop": true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment