Skip to content

Commit

Permalink
improve task
Browse files Browse the repository at this point in the history
  • Loading branch information
willybrauner committed Jul 4, 2023
1 parent 38bb151 commit cb12f91
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 94 deletions.
2 changes: 1 addition & 1 deletion apps/front/.env
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# base start & end with slash: /{base}/
VITE_APP_BASE=/
# protocol for server: http or https (default: http)
PROTOCOL=https
PROTOCOL=http

# ------------------------------------------------------------------------------ DOCKER

Expand Down
5 changes: 3 additions & 2 deletions apps/front/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
- [scaffold](#scaffold)
- [generate](#generate)
- [Vite plugins](#vite-plugins)
- [Setup local SSL](#setup-local-ssl)

## About

Expand Down Expand Up @@ -202,13 +203,13 @@ htaccessTemplateFilePath: resolve("src/.htaccess")

## Setup local SSL

- Generate a self-signed certificate in `apps/front` root folder
- Generate a self-signed certificate from `apps/front` root folder:

```shell
sudo openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
```

- Trust the certificate
- Trust the certificate:

```shell
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain cert.pem
Expand Down
175 changes: 84 additions & 91 deletions apps/front/server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import debug from "@wbe/debug"
import express from "express"
import * as fs from "fs"
import * as https from "https"
import * as mfs from "@wbe/mfs"
import portFinderSync from "portfinder-sync"
import { renderToPipeableStream } from "react-dom/server"
import { createServer, loadEnv } from "vite"
Expand All @@ -15,105 +15,98 @@ const port = process.env.DOCKER_NODE_PORT ?? portFinderSync.getPort(3000)
const protocol = loadEnvVars.PROTOCOL ?? "http"
const isSSL = protocol === "https"

// Get cert and key for https
let key, cert
if (isSSL) {
if (!fs.existsSync("key.pem") || !fs.existsSync("cert.pem")) {
log("You need to generate a key and a cert file with openssl in the front/ directory")
process.exit(1)
}
key = fs.readFileSync("key.pem")
cert = fs.readFileSync("cert.pem")
}

/**
* Dev server
*
*
*/
async function createDevServer() {
const app = express()

// dev script to inject
const devScripts = {
js: [{ tag: "script", attr: { type: "module", src: "/src/index.tsx" } }],
;(async () => {
// Get cert and key for https
let key, cert
if (isSSL) {
if (!(await mfs.fileExists("key.pem")) || !(await mfs.fileExists("cert.pem"))) {
console.error(
"You need to generate a key and a cert file with openssl in the apps/front/ directory. Follow the README documentation 'setup-local-ssl'."
)
process.exit(1)
}
key = await mfs.readFile("key.pem")
cert = await mfs.readFile("cert.pem")
}

// Create Vite server in middleware mode.
// This disables Vite's own HTML serving logic and let the parent server take control.
// https://vitejs.dev/config/server-options.html#server-middlewaremode
const vite = await createServer({
logLevel: "info",
server: {
middlewareMode: true,
https: isSSL && {
key,
cert,
},
cors: false,
},
appType: "custom",
})
/**
* Dev server
*
*
*/
async function createDevServer() {
const app = express()

// use vite's connect instance as middleware
app.use(vite.middlewares)
app.use("*", async (req, res, next) => {
try {
// Transforms the ESM source code to be usable in Node.js
const { render } = await vite.ssrLoadModule(
`${config.srcDir}/server/index-server.tsx`
)
// Get react-dom from the render method
const dom = await render(req.originalUrl, devScripts, false)
// Create stream with renderToPipeableStream to support Suspense API
const stream = renderToPipeableStream(dom, {
onShellReady() {
res.setHeader("Content-type", "text/html")
res.statusCode = 200
stream.pipe(res)
},
onError(e) {
res.statusCode = 500
console.error(e)
},
})
} catch (e) {
vite.ssrFixStacktrace(e)
next(e)
// dev script to inject
const devScripts = {
js: [{ tag: "script", attr: { type: "module", src: "/src/index.tsx" } }],
}
})

let sslServer
if (isSSL) {
sslServer = https.createServer(
{
key,
cert,
// Create Vite server in middleware mode.
// This disables Vite's own HTML serving logic and let the parent server take control.
// https://vitejs.dev/config/server-options.html#server-middlewaremode
const vite = await createServer({
logLevel: "info",
server: {
middlewareMode: true,
https: (isSSL && { key, cert }) || false,
cors: false,
},
app
)
appType: "custom",
})

sslServer.on("error", (error) => {
log(`Error on server: ${error}`)
// use vite's connect instance as middleware
app.use(vite.middlewares)
app.use("*", async (req, res, next) => {
try {
// Transforms the ESM source code to be usable in Node.js
const { render } = await vite.ssrLoadModule(
`${config.srcDir}/server/index-server.tsx`
)
// Get react-dom from the render method
const dom = await render(req.originalUrl, devScripts, false)
// Create stream with renderToPipeableStream to support Suspense API
const stream = renderToPipeableStream(dom, {
onShellReady() {
res.setHeader("Content-type", "text/html")
res.statusCode = 200
stream.pipe(res)
},
onError(e) {
res.statusCode = 500
console.error(e)
},
})
} catch (e) {
vite.ssrFixStacktrace(e)
next(e)
}
})
}

// return vite, app and server
return { vite, app, server: sslServer }
}
let sslServer
if (isSSL) {
sslServer = https.createServer({ key, cert }, app)
sslServer.on("error", (error) => {
log(`Error on server: ${error}`)
})
}

/**
* Production server
* TODO
*
*
*/
async function createProdServer() {}
// return vite, app and server
return { vite, app, sslServer }
}

/**
* Let's go!
*/
/**
* Production server
* TODO
*
*
*/
async function createProdServer() {}

;(isProduction ? createProdServer : createDevServer)().then(({ app, server }) =>
(server ?? app).listen(port)
)
/**
* Let's go!
*/
;(isProduction ? createProdServer : createDevServer)().then(({ app, sslServer }) =>
(sslServer ?? app).listen(port)
)
})()

0 comments on commit cb12f91

Please sign in to comment.