Last active
April 21, 2024 03:38
-
-
Save CharlieGreenman/4f3e5aa032e7a3aef3f7837a816b2b90 to your computer and use it in GitHub Desktop.
server.ts for serverless-express purposes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'zone.js/node'; | |
import { APIGatewayEvent, Context, APIGatewayProxyResult } from 'aws-lambda'; | |
import { APP_BASE_HREF } from '@angular/common'; | |
import * as express from 'express'; | |
import { CommonEngine } from '@angular/ssr'; | |
import { existsSync } from 'fs'; | |
import { join } from 'path'; | |
export const REQUEST = new InjectionToken<Request>('REQUEST'); | |
export const RESPONSE = new InjectionToken<Response>('RESPONSE'); | |
import { AppServerModule } from './src/main.server'; | |
import compression from 'compression'; | |
import * as mime from 'mime'; | |
import bodyParser from 'body-parser'; | |
// The Express app is exported so that it can be used by serverless Functions. | |
export function app(): express.Express { | |
const server = express(); | |
const distFolder = join(process.cwd(), 'dist/apps/frontend/browser'); | |
const indexHtml = existsSync(join(distFolder, 'index.original.html')) | |
? join(distFolder, 'index.original.html') | |
: join(distFolder, 'index.html'); | |
// Configure Headers for Security | |
// eslint-disable-next-line @typescript-eslint/no-var-requires | |
const helmet = require('helmet'); | |
const cookieParser = require('cookie-parser'); | |
server.use(helmet.noSniff()); | |
server.use(helmet.xssFilter()); | |
server.use(helmet.hsts()); | |
server.use(helmet.frameguard()); | |
server.use(cookieParser()); | |
server.disable('x-powered-by') | |
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/main/modules/express-engine) | |
const commonEngine = new CommonEngine(); | |
const compressor = compression(); | |
server.use('*.js', compressor); | |
server.use((req, res, next) => { | |
const mimeType = mime.getType(req.url); | |
if (mimeType) { | |
res.setHeader('Content-Type', mimeType); | |
} | |
}); | |
server.set('view engine', 'html'); | |
server.set('views', distFolder); | |
// Example Express Rest API endpoints | |
// server.get('/api/**', (req, res) => { }); | |
// Serve static files from /browser | |
server.get( | |
'*.*', | |
express.static(distFolder, { | |
maxAge: '1y', | |
}) | |
); | |
server.get('*', (req, res, next) => { | |
// console.log('req'); | |
// console.log(req.cookies); | |
const { protocol, originalUrl, baseUrl, headers } = req; | |
if (req.url === '/null') { | |
res.status(200).send(); | |
return; // fail silently and return from the function | |
} | |
// if(req.cookies.visited && req.cookies.currentRelativeUrl && req.url === '/') { | |
// res.redirect(req.cookies.currentRelativeUrl); | |
// return; | |
// } | |
commonEngine | |
.render({ | |
bootstrap: AppServerModule, | |
documentFilePath: indexHtml, | |
url: `${protocol}://${headers.host}${originalUrl}`, | |
publicPath: distFolder, | |
providers: [ | |
{ provide: APP_BASE_HREF, useValue: req.baseUrl }, | |
{ provide: REQUEST, useValue: req }, | |
{ provide: RESPONSE, useValue: res }, | |
], | |
}) | |
.then((html) => res.send(html)) | |
.catch((err) => next(err)); | |
}); | |
return server; | |
} | |
function run(): void { | |
const port = process.env['PORT'] || 4000; | |
// Start up the Node server | |
const server = app(); | |
server.listen(port, () => { | |
console.log(`Node Express server listening on http://localhost:${port}`); | |
}); | |
} | |
// Webpack will replace 'require' with '__webpack_require__' | |
// '__non_webpack_require__' is a proxy to Node 'require' | |
// The below code is to ensure that the server is run only when not requiring the bundle. | |
declare const __non_webpack_require__: NodeRequire; | |
const mainModule = __non_webpack_require__.main; | |
const moduleFilename = (mainModule && mainModule.filename) || ''; | |
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) { | |
run(); | |
} | |
export * from './src/main.server'; | |
// import serverlessExpress, { getCurrentInvoke } from '@codegenie/serverless-express'; | |
import serverlessExpress from '@codegenie/serverless-express'; | |
import { InjectionToken } from '@angular/core'; | |
const server = app(); | |
server.use(bodyParser.json()); | |
server.use(bodyParser.urlencoded({ extended: true })); | |
export const lambda_handler = (event: APIGatewayEvent, context: Context): Promise<APIGatewayProxyResult> => { | |
// const { event, context } = getCurrentInvoke() | |
console.log(`Event: ${JSON.stringify(event)}`); | |
console.log(`Context: ${JSON.stringify(context)}`); | |
if(context) { | |
context.callbackWaitsForEmptyEventLoop = false; | |
} | |
try { | |
const serverlessExpressInstance = serverlessExpress({ | |
app: server | |
}); | |
return serverlessExpressInstance(event, context); | |
} catch (err) { | |
console.log(err); | |
throw err; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment