Skip to content

Instantly share code, notes, and snippets.

@drewwiens
Last active October 22, 2021 15:26
Show Gist options
  • Save drewwiens/56f9e784fffa74ea17e6a78a0d820440 to your computer and use it in GitHub Desktop.
Save drewwiens/56f9e784fffa74ea17e6a78a0d820440 to your computer and use it in GitHub Desktop.
NestJS module to serve a single page app and set its base href from an environment variable on startup
import { join } from 'path';
import { Module } from '@nestjs/common';
import { ServeStaticModule } from '@nestjs/serve-static';
import { replaceInFile } from 'replace-in-file';
const STATIC_FILES_DIR = join(__dirname, 'client');
const YOUR_GLOBAL_PREFIX = 'api'; // Typically imported from some other file
@Module({
imports: [
// For deployments, serve frontend's dist files from "client" folder on disk
// relative to main.js; see https://github.com/nestjs/serve-static
ServeStaticModule.forRoot({
rootPath: STATIC_FILES_DIR,
// Serve static files only from non-api paths so that 404 is returned
// instead of index.html when an API URL doesn't match an API endpoint:
renderPath: new RegExp(`^/(?!${YOUR_GLOBAL_PREFIX}/).*`),
}),
ApiUtilConfigModule,
],
exports: [ServeStaticModule],
})
export class ServeStaticFilesModule {
constructor(private apiConfigSvc: ApiConfigService) {
this.writeBaseHref();
}
/**
* Set the frontend's base href tag with the value from the environment
* variable by writing it to the index.html file when the server starts.
*
* This allows the same static files to be deployed at any URL e.g. by
* a load balancer.
*/
private async writeBaseHref() {
const baseHref = process.env.BASE_HREF || '/';
const indexHtmlPath = join(STATIC_FILES_DIR, 'index.html');
const newBaseHrefTag = `<base href="${baseHref}"`;
try {
const result = await replaceInFile({
files: indexHtmlPath,
from: /<base\s+href=".*"/,
to: newBaseHrefTag,
});
console.log(
`Wrote base href "${baseHref}" to disk at "${indexHtmlPath}". Result:`,
result,
);
} catch (error) {
const details = error instanceof Error ? error.message : error;
console.error(
'Error writing base href. Base href may not have been set. Details:',
details,
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment