$ yarn
$ mkdir -p ssl/
$ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl/foobar.key -out ssl/foobar.crt
$ node server
Last active
April 7, 2021 10:04
-
-
Save maraisr/b60902d582ccbf915f9d7dbcbdeef08d to your computer and use it in GitHub Desktop.
Streaming React with Server Timings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"type":"module", | |
"dependencies": { | |
"polka": "^1.0.0-next.14", | |
"react": "^17.0.2", | |
"react-dom": "^17.0.2" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {createServer} from 'https' | |
import polka from 'polka'; | |
import {readFileSync} from 'fs'; | |
import {createElement} from 'react'; | |
import {renderToStaticNodeStream} from 'react-dom/server.node.js'; | |
const options = { | |
key: readFileSync('ssl/foobar.key'), | |
cert: readFileSync('ssl/foobar.crt') | |
}; | |
const { handler } = polka() | |
.get('/', (_, res) => { | |
console.log('~> req'); | |
res.setHeader('Content-Type', 'text/html; charset=UTF-8'); | |
res.setHeader('Transfer-Encoding', 'chunked'); | |
res.setHeader('Trailer', 'Server-Timing'); | |
res.flushHeaders(); | |
const start = Date.now(); | |
const stream = renderToStaticNodeStream( | |
createElement('html', null, createElement('body', null, createElement('p', null, 'hello world'))) | |
); | |
stream.pipe(res, {end: false}); | |
stream.on('end', () => { | |
res.addTrailers({'Server-Timing': `render;dur=${Date.now() - start}`}); | |
console.log('~> ended'); | |
res.end(); | |
}); | |
}); | |
createServer(options, handler).listen(8080, (e) => { | |
if (e) return (console.error(e), void process.exit(1)); | |
console.log(`~> Running on https://localhost:${8080}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment