Skip to content

Commit

Permalink
Fix: serve React app and its assets correctly within Express app.
Browse files Browse the repository at this point in the history
  • Loading branch information
dleclercpro committed Dec 13, 2023
1 parent bce2bb2 commit cbf0048
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 6 deletions.
3 changes: 1 addition & 2 deletions Apps/Server/src/config/AppConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,4 @@ export const ROOT = `${createURL(PROTOCOL, HOST, PORT)}/`;
export const CLIENT_PROTOCOL = process.env.CLIENT_PROTOCOL!;
export const CLIENT_HOST = process.env.CLIENT_HOST!;
export const CLIENT_PORT = parseInt(process.env.CLIENT_PORT!);
export const CLIENT_ROOT = createURL(CLIENT_PROTOCOL, CLIENT_HOST, CLIENT_PORT);
export const CLIENT_DIRECTORY = 'client';
export const CLIENT_ROOT = createURL(CLIENT_PROTOCOL, CLIENT_HOST, CLIENT_PORT);
3 changes: 3 additions & 0 deletions Apps/Server/src/config/ResourceConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import path from 'path';

export const CLIENT_DIR = path.join(__dirname, `../..`, `client`);
24 changes: 21 additions & 3 deletions Apps/Server/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import express, { Router } from 'express';
import { RequestMiddleware } from '../middleware/RequestMiddleware';
import { CLIENT_DIRECTORY, CLIENT_ROOT, PROD } from '../config/AppConfig';
import { CLIENT_ROOT, PROD } from '../config/AppConfig';
import ApiRouter from './api';
import { logger } from '../utils/logger';
import path from 'path';
import { CLIENT_DIR } from '../config/ResourceConfig';



Expand All @@ -21,12 +24,27 @@ router.use(`/api`, ApiRouter);

// Client app
if (PROD) {
router.use('/', express.static(CLIENT_DIRECTORY));

// Serve React app's static files
router.use(express.static(path.join(CLIENT_DIR)));

// Define a route that serves the React app
router.get('*', (req, res) => {
const url = path.join(CLIENT_DIR, 'index.html');

logger.trace(`Serving client app from: ${url}`);

return res.sendFile(url);
});
} else {
router.use('/', (req, res, next) => {

// Redirect app to React's development server
router.get('*', (req, res, next) => {
const path = req.originalUrl;
const url = `${CLIENT_ROOT}${path}`;

logger.trace(`Redirecting request to: ${url}`);

return res.redirect(url);
});
}
Expand Down
2 changes: 1 addition & 1 deletion Apps/Server/src/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const DEV_OPTIONS = {
};

const PROD_OPTIONS = {
level: 'trace',
level: 'debug',
};

export const logger = pino(PROD ? PROD_OPTIONS : DEV_OPTIONS);

0 comments on commit cbf0048

Please sign in to comment.