Add dev-proxy to frontend dev server

This adds a reverse proxy to the backend, that automatically
redirects requests that are not handled by the backend to the React
dev server running on port 3001.

The reverse proxy is only enabled when NODE_ENV is set to
'development'.

Signed-off-by: David Mehren <git@herrmehren.de>
This commit is contained in:
David Mehren 2021-09-23 22:36:13 +02:00
parent e5750b0084
commit a4749d60f7
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
5 changed files with 113 additions and 2 deletions

View file

@ -0,0 +1,35 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { NestExpressApplication } from '@nestjs/platform-express';
import { createProxyMiddleware } from 'http-proxy-middleware';
import { ConsoleLoggerService } from '../logger/console-logger.service';
import { useUnless } from './use-unless';
export function setupFrontendProxy(
app: NestExpressApplication,
logger: ConsoleLoggerService,
): void {
logger.log(
`Setting up proxy to frontend dev server on port 3001`,
'setupFrontendProxy',
);
const frontendProxy = createProxyMiddleware({
logProvider: () => {
return {
log: (msg) => logger.log(msg, 'FrontendProxy'),
debug: (msg) => logger.debug(msg, 'FrontendProxy'),
info: (msg) => logger.log(msg, 'FrontendProxy'),
warn: (msg) => logger.warn(msg, 'FrontendProxy'),
error: (msg) => logger.error(msg, 'FrontendProxy'),
};
},
target: 'http://localhost:3001',
changeOrigin: true,
ws: true,
});
app.use(useUnless(['/api', '/public'], frontendProxy));
}

18
src/utils/use-unless.ts Normal file
View file

@ -0,0 +1,18 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { NextFunction, Request, Response } from 'express';
export function useUnless(
paths: string[],
middleware: (req: Request, res: Response, next: NextFunction) => unknown,
) {
return function (req: Request, res: Response, next: NextFunction): unknown {
if (paths.some((path) => req.path.startsWith(path))) {
return next();
}
return middleware(req, res, next);
};
}