@@ -2,15 +2,21 @@ import type Express from "@types/express";
22import type { NextFunction } from "@types/express" ;
33import { configDotenv } from "dotenv" ;
44import express from "express" ;
5+ import fs from "fs" ;
56import http , { Server } from "http" ;
67import path from "path" ;
8+ import process from "process" ;
9+ import React , { ReactNode } from "react" ;
10+ import { renderToString } from "react-dom/server" ;
11+ import App from "~/App" ;
712
813const app : Express . Application = express ( ) ;
914
1015configDotenv ( { override : true , quiet : true } ) ;
1116
1217app . use ( express . json ( ) ) ;
13- app . use ( express . static ( "dist" ) ) ;
18+ app . use ( "/assets" , express . static ( "dist/assets" ) ) ;
19+ app . use ( "/favicon.ico" , express . static ( "dist/favicon.ico" ) ) ;
1420
1521app . get (
1622 "/api/proxy" ,
@@ -81,10 +87,38 @@ app.post(
8187 } ,
8288) ;
8389
84- app . get ( "*fallback" , ( _ , res : Express . Response ) : void => {
85- res . sendFile ( path . join ( path . resolve ( ) , "dist/index.html" ) ) ;
90+ //app.use(vite.middlewares);
91+
92+ app . use ( "*all" , ( req : Express . Request , res : Express . Response ) : void => {
93+ const url : string = req . originalUrl ;
94+
95+ const app : ReactNode = React . createElement ( App , { url : url } ) ;
96+
97+ const indexPath : string = path . join ( path . resolve ( ) , "dist/index.html" ) ;
98+
99+ let isNotFound : boolean = false ;
100+
101+ let rendered : string ;
102+ try {
103+ rendered = renderToString ( app ) ;
104+ } catch ( e ) {
105+ if ( e . message === "404_NOT_FOUND" ) {
106+ isNotFound = true ;
107+ rendered = "<span>404 - Not found</span>" ;
108+ }
109+ }
110+
111+ const template : string = fs . readFileSync ( indexPath , "utf-8" ) ;
112+
113+ const html : string = template . replace ( "<!--root-->" , rendered ) ;
114+
115+ res . status ( isNotFound ? 404 : 200 ) . send ( html ) ;
86116} ) ;
87117
88- const server : Server = http . createServer ( app ) . listen ( 3000 ) ;
118+ const port : number = parseInt ( process . env . SERVER_PORT ) || 3000 ;
119+
120+ const server : Server = http . createServer ( app ) . listen ( port , ( ) : void => {
121+ console . info ( `Server is running in port ${ port } .` ) ;
122+ } ) ;
89123
90124export default server ;
0 commit comments