CrazyCoder
CrazyCoder

Reputation: 219

Angular Universal SSR + Serverless Framework ReferenceError: Event is not defined when Trigger the URL

I'm Trying to add SSR for my angular application and after days i was able to finally Build it right.

Build Command : npm run build:ssr

Out Put :

 Generating ES5 bundles for differential loading...
ES5 bundle generation complete.

chunk {3} polyfills-es2015.458aac6b11c541194b4a.js (polyfills) 58.5 kB [initial] [rendered]
chunk {4} polyfills-es5.44c9dea30eed52ba4506.js (polyfills-es5) 150 kB [initial] [rendered]
chunk {2} main-es2015.3ba2902bcbc10c1675ba.js (main) 3.36 MB [initial] [rendered]
chunk {2} main-es5.3ba2902bcbc10c1675ba.js (main) 3.58 MB [initial] [rendered]
chunk {6} 6-es2015.53bbc3626530cc9d62a6.js () 875 kB  [rendered]
chunk {6} 6-es5.53bbc3626530cc9d62a6.js () 875 kB  [rendered]
chunk {0} runtime-es2015.a4937581a2ac14eb4b95.js (runtime) 2.31 kB [entry] [rendered]
chunk {0} runtime-es5.a4937581a2ac14eb4b95.js (runtime) 2.31 kB [entry] [rendered]
chunk {1} 1-es2015.1db2b7e193a26ab34e26.js () 14.8 kB  [rendered]
chunk {1} 1-es5.1db2b7e193a26ab34e26.js () 19.3 kB  [rendered]
chunk {7} 7-es2015.49a93052cb35da6a7127.js () 92 bytes  [rendered]
chunk {7} 7-es5.49a93052cb35da6a7127.js () 92 bytes  [rendered]
chunk {8} 8-es2015.f442eec7404ae5a74fa8.js () 2.87 kB  [rendered]
chunk {8} 8-es5.f442eec7404ae5a74fa8.js () 2.87 kB  [rendered]
chunk {5} styles.dd45993893183a374073.css (styles) 260 kB [initial] [rendered]
Date: 2020-05-05T23:11:30.255Z - Hash: 237a75faa10dbd147775 - Time: 74145ms
Hash: b0b68963644c131250a2
Time: 42240ms
Built at: 05/05/2020 7:12:16 PM
                                             Asset       Size  Chunks                    Chunk Names
                     highlight-js-lib-highlight.js  219 bytes       1  [emitted]         highlight-js-lib-highlight
                    highlightjs-line-numbers-js.js   9.92 KiB       2  [emitted]         highlightjs-line-numbers-js
                                           main.js   19.5 MiB       3  [emitted]  [big]  main
                           vendors~highlight-js.js   1.07 MiB       4  [emitted]  [big]  vendors~highlight-js
vendors~highlight-js~highlight-js-lib-highlight.js   45.4 KiB       0  [emitted]         vendors~highlight-js~highlight-js-lib-highlight
Entrypoint main [big] = main.js
chunk    {0} vendors~highlight-js~highlight-js-lib-highlight.js (vendors~highlight-js~highlight-js-lib-highlight) 45.3 KiB <{3}> ={1}= ={4}= [rendered] split chunk (cache group: vendors) (name: vendors~highlight-js~highlight-js-lib-highlight)
chunk    {1} highlight-js-lib-highlight.js (highlight-js-lib-highlight) 83 bytes <{3}> ={0}= [rendered]
chunk    {2} highlightjs-line-numbers-js.js (highlightjs-line-numbers-js) 9.81 KiB <{3}> [rendered]
chunk    {3} main.js (main) 19.1 MiB >{0}< >{1}< >{2}< >{4}< [entry] [rendered]
chunk    {4} vendors~highlight-js.js (vendors~highlight-js) 1.06 MiB <{3}> ={0}= [rendered] split chunk (cache group: vendors) (name: vendors~highlight-js)

> [email protected] compile:server /Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart
> webpack --config webpack.server.config.js --progress --colors

Hash: 3b040255852c8146c5c5
Version: webpack 4.39.2
Time: 22584ms
Built at: 05/05/2020 7:12:49 PM
    Asset      Size  Chunks             Chunk Names
server.js  26.4 MiB       0  [emitted]  server
Entrypoint server = server.js
  [0] ./server.ts 1.99 KiB {0} [built]
  [2] external "events" 42 bytes {0} [built]
  [3] external "fs" 42 bytes {0} [built]
  [4] external "timers" 42 bytes {0} [optional] [built]
  [5] external "crypto" 42 bytes {0} [built]
 [13] external "path" 42 bytes {0} [built]
 [36] external "buffer" 42 bytes {0} [built]
 [57] external "stream" 42 bytes {0} [built]
 [62] external "zlib" 42 bytes {0} [built]
 [83] external "url" 42 bytes {0} [built]
 [90] external "http" 42 bytes {0} [built]
[286] external "child_process" 42 bytes {0} [built]
[297] external "https" 42 bytes {0} [built]
[572] external "os" 42 bytes {0} [built]
[793] ./dist/server/main.js 19.5 MiB {0} [built]
    + 786 hidden modules

WARNING in ./node_modules/jsdom/lib/jsdom/utils.js 216:21-40
Critical dependency: the request of a dependency is an expression
 @ ./node_modules/jsdom/lib/jsdom.js
 @ ./node_modules/mock-browser/lib/MockBrowser.js
 @ ./node_modules/mock-browser/index.js
 @ ./server.ts

then I want to test it using serverless offline : npm run serve:ssr

> serverless offline start

Serverless: Starting Offline: ENGG/us-east-1.

Serverless: Routes for api:
Serverless: ANY /{proxy*}
Serverless: ANY /
Serverless: POST /{apiVersion}/functions/ibrainmart-ENGG-api/invocations

Serverless: Offline [HTTP] listening on http://localhost:3000
Serverless: Enter "rp" to replay the last request

Serverless: ANY /ENGG (λ: api)
Serverless: Error while loading api

Now the Problem is when i try to invoke URL : http://localhost:3000 I'm Getting Below error

Serverless: ANY /ENGG (λ: api)
Serverless: Error while loading api
ReferenceError: Event is not defined
    at /Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:328709:42
    at Module.KL2N (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:328719:2)
    at __webpack_require__ (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:169209:30)
    at Object.V7fC (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:456942:14)
    at __webpack_require__ (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:169209:30)
    at Object.K011 (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:327243:37)
    at __webpack_require__ (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:169209:30)
    at Object.0 (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:174669:18)
    at __webpack_require__ (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:169209:30)
    at /Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:169300:18
    at Object.<anonymous> (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:169303:10)
    at __webpack_require__ (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:21:30)
    at Module.<anonymous> (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:132:91)
    at __webpack_require__ (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:21:30)
    at /Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:85:18
    at Object.<anonymous> (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/dist/server.js:88:10)
    at Module._compile (internal/modules/cjs/loader.js:777:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:788:10)
    at Module.load (internal/modules/cjs/loader.js:643:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:683:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at Object.<anonymous> (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/lambda.js:2:16)
    at Module._compile (internal/modules/cjs/loader.js:777:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:788:10)
    at Module.load (internal/modules/cjs/loader.js:643:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:683:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at Object.createHandler (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/node_modules/serverless-offline/src/functionHelper.js:215:15)
    at handler (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/node_modules/serverless-offline/src/ApiGateway.js:485:40)
    at module.exports.internals.Manager.execute (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/node_modules/@hapi/hapi/lib/toolkit.js:41:33)
    at Object.internals.handler (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/node_modules/@hapi/hapi/lib/handler.js:46:48)
    at exports.execute (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/node_modules/@hapi/hapi/lib/handler.js:31:36)
    at Request._lifecycle (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/node_modules/@hapi/hapi/lib/request.js:312:68)
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
    at Request._execute (/Users/liyanaarachchi/[email protected]/Serverless Framwork/WebApplication/ibrainmart/node_modules/@hapi/hapi/lib/request.js:221:9)

This is My Server.ts File

import 'zone.js/dist/zone-node';

import * as express from 'express';
import * as compression from 'compression';
import * as cors from 'cors';
import * as bodyParser from 'body-parser';
import { join } from 'path';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
const MockBrowser = require('mock-browser').mocks.MockBrowser;
import { resolve } from 'path';

const domino = require('domino');
const win = domino.createWindow('');

const mock = new MockBrowser();

global['navigator'] = mock.getNavigator();
global['window'] = win;
global['document'] = win.document;
global['XMLHttpRequest'] = require('xmlhttprequest').XMLHttpRequest;

// Express server
export const app = express();

app.use(compression());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const DIST_FOLDER = join(process.cwd(), 'dist/browser');

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {
  AppServerModuleNgFactory,
  LAZY_MODULE_MAP,
  ngExpressEngine,
  provideModuleMap,
} = require('./dist/server/main');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', (_, options, callback) => {
  const engine = ngExpressEngine({
    bootstrap: AppServerModuleNgFactory,
    providers: [
      provideModuleMap(LAZY_MODULE_MAP),
    ],
  });

  engine(_, options, callback);
});

app.set('view engine', 'html');
app.set('views', DIST_FOLDER);

// Example Express Rest API endpoints
// app.get('/api/**', (req, res) => { });
// Serve static files from /browser
app.get(
  '*.*',
  express.static(DIST_FOLDER, {
    maxAge: '1y',
  }),
);

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render('index', { req, res }, (err, html) => {
    if (html) {
      if (req.headers.host.indexOf('amazonaws.com') > 0) {
        html = html.replace('<base href="/', '<base href="/dev/');
      }
      res.send(html);
    } else {
      res.send(err);
    }
  });
});

and this my lambda function

const awsServerlessExpress = require('aws-serverless-express');
const server = require('./dist/server');
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware');

const binaryMimeTypes = [
  'application/javascript',
  'application/json',
  'application/octet-stream',
  'application/xml',
  'image/jpeg',
  'image/png',
  'image/gif',
  'text/comma-separated-values',
  'text/css',
  'text/html',
  'text/javascript',
  'text/plain',
  'text/text',
  'text/xml',
  'image/x-icon',
  'image/svg+xml',
  'application/x-font-ttf',
  'font/ttf',
  'font/otf',
];

server.app.use(awsServerlessExpressMiddleware.eventContext());

const serverProxy = awsServerlessExpress.createServer(server.app, null, binaryMimeTypes);
module.exports.handler = async (event, context) => {awsServerlessExpress.proxy(serverProxy, event, context);}

Does anyone know how to resolve this issue ..?

My Package.json


{
  "name": "ibrainmart",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "compile:server": "webpack --config webpack.server.config.js --progress --colors",
    "serve:ssr": "serverless offline start",
    "build:ssr": "npm run build:client-and-server-bundles && npm run compile:server",
    "deploy": "serverless deploy",
    "terminate": "serverless remove",
    "build:client-and-server-bundles": "ng build --prod && ng run ibrainmart:server:production --bundleDependencies all"
  },
  "private": true,
  "dependencies": {
    "@angular/platform-server": "~8.2.13",
    "@nguniversal/express-engine": "^8.2.6",
    "@nguniversal/module-map-ngfactory-loader": "v8.2.6",
    "aws-serverless-express": "^3.3.6",
    "cors": "^2.8.5",
    "express": "^4.15.2",
    "@aws-amplify/auth": "^3.2.6",
    "@agm/core": "^1.1.0",
    "@angular/animations": "^8.1.3",
    "@angular/cdk": "^8.2.3",
    "@angular/common": "~8.1.3",
    "@angular/compiler": "~8.1.3",
    "@angular/core": "~8.1.3",
    "@angular/forms": "~8.1.3",
    "@angular/material": "^8.1.2",
    "@angular/platform-browser": "~8.1.3",
    "@angular/platform-browser-dynamic": "~8.1.3",
    "@angular/router": "~8.1.3",
    "@aws-amplify/ui": "^1.0.23",
    "@elastic/elasticsearch": "^7.6.1",
    "@fortawesome/angular-fontawesome": "^0.5.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-brands-svg-icons": "^5.13.0",
    "@fortawesome/free-solid-svg-icons": "^5.13.0",
    "@ng-bootstrap/ng-bootstrap": "^5.1.1",
    "@ng-select/ng-select": "^3.0.7",
    "@ng-toolkit/universal": "^7.1.2",
    "@ngx-share/button": "^7.1.4",
    "@ngx-share/buttons": "^7.1.4",
    "@ngx-share/core": "^7.1.4",
    "angular-animate": "^1.7.8",
    "angular-bootstrap-datetimepicker": "^4.0.2",
    "angular-font-awesome": "^3.1.2",
    "angular-material": "^1.1.19",
    "angular-messages": "^1.7.8",
    "angular-multiple-select": "^1.1.3",
    "angular-popper": "^2.0.1",
    "angular-sortablejs": "^2.7.0",
    "aws-amplify": "^1.1.36",
    "aws-amplify-angular": "^3.0.11",
    "aws-elasticsearch-client": "^2.0.0",
    "aws-sdk": "^2.648.0",
    "bootstrap": "^4.4.1",
    "bootstrap-table": "^1.15.3",
    "bootstrap4-toggle": "^3.5.0",
    "buffer": "^5.5.0",
    "date-fns": "^2.11.0",
    "dropify": "^0.2.2",
    "e": "0.0.4",
    "elasticsearch": "^16.7.1",
    "elasticsearch-browser": "^16.7.1",
    "font-awesome": "^4.7.0",
    "guid-typescript": "^1.0.9",
    "jquery": "^3.4.1",
    "material-design-icons": "^3.0.1",
    "moment": "^2.24.0",
    "ng-pick-datetime": "^7.0.0",
    "ng-sortgrid": "^1.3.3",
    "ng-zorro-antd": "^8.5.2",
    "ngx-bootstrap": "^5.1.1",
    "ngx-float-button": "^1.0.0",
    "ngx-google-places-autocomplete": "^2.0.4",
    "ngx-highlightjs": "^4.0.2",
    "ngx-image-cropper": "^2.1.2",
    "ngx-image-editor": "^1.4.1",
    "ngx-paypal": "^5.0.0",
    "ngx-quill": "^7.3.12",
    "ngx-select-dropdown": "^1.1.0",
    "ngx-sortablejs": "^3.1.3",
    "open-iconic": "^1.1.1",
    "paypal-checkout": "^4.0.308",
    "popper.js": "^1.15.0",
    "quill": "^1.3.7",
    "rxjs": "~6.4.0",
    "sortablejs": "^1.10.0-rc3",
    "tslib": "^1.9.0",
    "zone.js": "~0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/architect": "~0.803.20",
    "@angular-devkit/build-angular": "~0.803.20",
    "@angular-devkit/core": "~8.3.20",
    "@angular-devkit/schematics": "~8.3.20",
    "@angular/cli": "^8.3.23",
    "@angular/compiler-cli": "~8.1.3",
    "@angular/language-service": "~8.1.3",
    "@types/googlemaps": "^3.39.1",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/jquery": "^3.3.31",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "timelite": "^1.0.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.4.3",
    "serverless": "^1.60.5",
    "serverless-apigw-binary": "^0.4.4",
    "serverless-offline": "^5.12.1",
    "ts-loader": "^5.2.0",
    "webpack-cli": "^3.1.0"
  }
}

Upvotes: 0

Views: 1823

Answers (1)

David
David

Reputation: 34455

This is because one of your dependencies is trying to access the Event object, which is not available by default server side.

Since you are already using domino, you can try adding these lines to your server.ts to make Event object available

//other global declarations
global['Event'] = win.Event;
global['Event']['prototype'] = win.Event.prototype;
global['KeyboardEvent'] = win.Event;
global['MouseEvent'] = win.Event;

Upvotes: 1

Related Questions