Giter Site home page Giter Site logo

nestjs / ng-universal Goto Github PK

View Code? Open in Web Editor NEW
440.0 10.0 67.0 3.16 MB

Angular Universal module for Nest framework (node.js) 🌷

Home Page: https://nestjs.com

License: MIT License

JavaScript 1.50% TypeScript 98.50%
nestjs nest angular angular-universal server-side-rendering nodejs typescript

ng-universal's Introduction

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads Coverage Discord Backers on Open Collective Sponsors on Open Collective

Description

Angular Universal module for Nest.

Installation

Using the Angular CLI:

$ ng add @nestjs/ng-universal

Or manually:

$ npm i @nestjs/ng-universal

Example

See full example here.

Usage

If you have installed the module manually, you need to import AngularUniversalModule in your Nest application.

import { Module } from '@nestjs/common';
import { join } from 'path';
import { AngularUniversalModule } from '@nestjs/ng-universal';

@Module({
  imports: [
    AngularUniversalModule.forRoot({
      bootstrap: AppServerModule,
      viewsPath: join(process.cwd(), 'dist/{APP_NAME}/browser')
    })
  ]
})
export class ApplicationModule {}

API Spec

The forRoot() method takes an options object with a few useful properties.

Property Type Description
viewsPath string The directory where the module should look for client bundle (Angular app)
bootstrap Function Angular server module reference (AppServerModule).
templatePath string? Path to index file (default: {viewsPaths}/index.html)
rootStaticPath string? Static files root directory (default: *.*)
renderPath string? Path to render Angular app (default: *)
extraProviders StaticProvider[]? The platform level providers for the current render request
inlineCriticalCss boolean? Reduce render blocking requests by inlining critical CSS. (default: true)
cache boolean? | object? Cache options, description below (default: true)
errorHandler Function? Callback to be called in case of a rendering error

Cache

Property Type Description
expiresIn number? Cache expiration in milliseconds (default: 60000)
storage CacheStorage? Interface for implementing custom cache storage (default: in memory)
keyGenerator CacheKeyGenerator? Interface for implementing custom cache key generation logic (default: by url)
AngularUniversalModule.forRoot({
  bootstrap: AppServerModule,
  viewsPath: join(process.cwd(), 'dist/{APP_NAME}/browser'),
  cache: {
    storage: new InMemoryCacheStorage(),
    expiresIn: DEFAULT_CACHE_EXPIRATION_TIME,
    keyGenerator: new CustomCacheKeyGenerator()
  }
});

Example for CacheKeyGenerator:

export class CustomCacheKeyGenerator implements CacheKeyGenerator {
  generateCacheKey(request: Request): string {
    const md = new MobileDetect(request.headers['user-agent']);
    const isMobile = md.mobile() ? 'mobile' : 'desktop';
    return (request.hostname + request.originalUrl + isMobile).toLowerCase();
  }
}

Request and Response Providers

This tool uses @nguniversal/express-engine and will properly provide access to the Express Request and Response objects in you Angular components. Note that tokens must be imported from the @nestjs/ng-universal/tokens, not @nguniversal/express-engine/tokens.

This is useful for things like setting the response code to 404 when your Angular router can't find a page (i.e. path: '**' in routing):

import { Response } from 'express';
import { Component, Inject, Optional, PLATFORM_ID } from '@angular/core';
import { isPlatformServer } from '@angular/common';
import { RESPONSE } from '@nestjs/ng-universal/tokens';

@Component({
  selector: 'my-not-found',
  templateUrl: './not-found.component.html',
  styleUrls: ['./not-found.component.scss']
})
export class NotFoundComponent {
  constructor(
    @Inject(PLATFORM_ID)
    private readonly platformId: any,
    @Optional()
    @Inject(RESPONSE)
    res: Response
  ) {
    // `res` is the express response, only available on the server
    if (isPlatformServer(this.platformId)) {
      res.status(404);
    }
  }
}

Custom Webpack

In some situations, it may be required to customize the webpack build while using @nestjs/ng-universal, especially when additional dependencies are included (that rely on native Node.js code).

To add a customizable webpack config to your project, it is recommended to install @angular-builders/custom-webpack in the project and to set your builders appropriately.

Example Custom Webpack

// webpack.config.ts
import { Configuration, IgnorePlugin } from 'webpack'
import {
  CustomWebpackBrowserSchema,
  TargetOptions
} from '@angular-builders/custom-webpack'
import nodeExternals from 'webpack-node-externals'

export default (
  config: Configuration
  _options: CustomWebpackBrowserSchema,
  targetOptions: TargetOptions
) => {
  if (targetOptions.target === 'server') {
    config.resolve?.extensions?.push('.mjs', '.graphql', '.gql')

    config.module?.rules?.push({
      test: /\.mjs$/,
      include: /node_modules/,
      type: 'javascript/auto'
    });

    config.externalsPresets = { node: true }

    (config.externals as Array<any>).push(
      nodeExternals({ allowlist: [/^(?!(livereload|concurrently|fsevents)).*/]})
    );

    config.plugins?.push(
      new IgnorePlugin({
        checkResource: (resource: string) => {
          const lazyImports = [
            '@nestjs/microservices',
            '@nestjs/microservices/microservices-module',
            '@nestjs/websockets/socket-module',
            'cache-manager',
            'class-validator',
            'class-transform',
          ];

          if (!lazyImpots.includes(resource)) {
            return false;
          }

          try {
            require.resolve(resource)
          } catch (_err: any) {
            return true;
          }
          return false;
        }
      })
    );
  }
  return config;
};

Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.

Stay in touch

License

Nest is MIT licensed.

ng-universal's People

Contributors

alexfriesen avatar arturovt avatar bartlomiejgawel avatar bpopnikolov avatar brunnerlivio avatar caucik avatar cwspear avatar dependabot[bot] avatar emmanueldemey avatar eternalmatt avatar forbiddencoding avatar freib avatar jboeijenga avatar kamilmysliwiec avatar macroorganizm avatar markpieszak avatar mfursov avatar micalevisk avatar oreofeolurin avatar quinnjr avatar renovate-bot avatar renovate[bot] avatar stephenfluin avatar tony133 avatar un33k avatar wodcz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ng-universal's Issues

Provide options other than nodemon, like "ng cli" for continued support of file replacements ?


[ ] Regression 
[ ] Bug report
[x ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Currently running the following script for "serving" and it works well but it seems to be hardcoded to use nodemon. I have my server already linked into angular cli using nx.

const { LiveReloadCompiler } = require("@nestjs/ng-universal")

const compiler = new LiveReloadCompiler({
  projectName: "test-ui",
  tsServerConfigFile: "apps/test-server/tsconfig.json",
  watchDir: "dist",
  serverBundlePath: "dist/apps/test-server-bundle/main.js",
  serverFilePath: "dist/apps/test-server/main",
  mainBundlePath: "dist/apps/test-ui/main.js",
  indexFilePath: "dist/apps/test-ui/index.html",
  outputDir: "dist",
  watchSsr: true
})
compiler.run()

It would be great if we could opt for "ng serve / build" to build the project and execute it rather than nodemon.

This allows us to continue using the file replacement in angular.json for production builds, i currently lose this ability using nodemon. Also the ng cli with nestjs brings so much to the table.

              "fileReplacements": [
                {
                  "replace": "apps/test-server/src/environments/environment.ts",
                  "with": "apps/test-server/src/environments/environment.prod.ts"
                }
              ],

I notice LiveReloadCompiler calls into NG cli to run UI build with this line

  projectName: "test-ui",

Would be nice if we can have an option for server so something like

  uiProjectName: "test-ui",
  serverProjectName: "test.server"

Both the above are available in the angular.json so both can be run via ng build or ng serve.

Environment


Nest version: 6.1
 
For Tooling issues:
- Node version: 11
- Platform:  MAC

Others:

Webpack is returning __dirname as '/'


[ ] Regression 
[x ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request 

Current behavior

When compiling to prod with build:ssr and serve:ssr it seems webpack is returning __dirname as "/" for swagger.

Minimal reproduction of the problem with instructions

Use @nestjs/ng-universal with default webpack config and default swagger config.

Environment

Ubuntu 18.04 and also local on Windows 10.
Node 10.16
Npm 6.9.0
NestJS 6.6.3
NestJS/Swagger 3.1.0
NestJS/ng-universal 2.1.0
Webpack-cli 3.3.7

Exact error im receiving is:
Unhandled Promise rejection: ENOENT: no such file or directory, open '//indexTemplate.html.tpl' ; Zone: <root> ; Task: Promise.then ; Value: { Error: ENOENT: no such file or directory, open '//indexTemplate.html.tpl' at Object.openSync (fs.js:438:3) at Object.readFileSync (fs.js:343:35) at Object.generateHTML (C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:80659:16) at Function.setupExpress (C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:79512:39) at Function.setup (C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:79505:21) at C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:129:33 at Generator.next (<anonymous>) at fulfilled (C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:95:58) at Zone.run (C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:1633:43) errno: -4058, syscall: 'open', code: 'ENOENT', path: '//indexTemplate.html.tpl' } Error: ENOENT: no such file or directory, open '//indexTemplate.html.tpl' at Object.openSync (fs.js:438:3) at Object.readFileSync (fs.js:343:35) at Object.generateHTML (C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:80659:16) at Function.setupExpress (C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:79512:39) at Function.setup (C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:79505:21) at C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:129:33 at Generator.next (<anonymous>) at fulfilled (C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:95:58) at ZoneDelegate.invoke (C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:1874:26) at Zone.run (C:\Users\Work\PhpstormProjects\terminal-app\dist\server.js:1633:43)
I tried doing __dirname: true/false but it seems that webpack-config.factory.d.ts is not accepting this param - so general workaround doesnt work.

Can't start production build

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

➜  ssr git:(master) ✗ yarn serve:ssr
yarn run v1.19.0
$ node dist/server
internal/modules/cjs/loader.js:783
    throw err;
    ^

Error: Cannot find module '/Users/i_skiridomov/Documents/Projects/koko/temp/ssr/dist/server'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:780:15)
    at Function.Module._load (internal/modules/cjs/loader.js:685:27)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1014:10)
    at internal/main/run_main_module.js:17:11 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Expected behavior

Server should start without errors and serve a requests

Minimal reproduction of the problem with instructions

ng new ssr
ng add @nestjs/ng-universal
yarn serve:ssr

What is the motivation / use case for changing the behavior?

Environment


Nest version: 6.10.2

 
For Tooling issues:
- Node version: 12.11.1  
- Platform:  Mac 

Others:

Bug when running install schematic with Nx workspace

I'm submitting a...


[ ] Regression 
[ x ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

I generated an Angular application using nrwl/nx.

I want to setup SSR with Nest using the install schematic but I get the following error instantly after answering the first question :

? What is the name of your application? web
Cannot read property 'kind' of undefined

I checked what does this error mean and it seems to come from the util for express-engine findAppServerModuleExport().

Expected behavior

Since nx natively supports Nest I'm expecting the install schematic working properly.

Minimal reproduction of the problem with instructions

I used angular-nest preset to generate my app

npx create-nx-workspace myworkspace --preset angular-nest

Then once my workspace was ready I ran the install schematic as described in the nestjs/ng-universal README.md, targeting the Angular application I generated just before.

ng add @nestjs/ng-universal

Environment

  • nest: 6.2.4
  • @nrwl/workspace: 8.4.13
  • @nrwl/angular: 8.4.13
  • @nrwl/nest: 8.4.13
  • @nrwl/node: 8.4.13

For Tooling issues:

  • Node version: 10.15.3
  • Platform: Linux

Build failures in master

I'm submitting a...


[x] Regression 
[ ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request

Current behavior

Typescript cannot compile

Expected behavior

Typescript compiles

Minimal reproduction of the problem with instructions

$ npm run build:schematics

What is the motivation / use case for changing the behavior?

I want the build to work so I can merge pull requests.

Environment

For Tooling issues:

  • Node version: 10.14.0
  • Platform: Windows

Others:
I tried bumping @types/node to latest, but this did not resolve the issue. Sorry, I haven't investigate further than this. I did notice that the merges on Nov 26 to master branch had failing commits as well (e.g. https://github.com/nestjs/ng-universal/commits/master)

Capture errors from angular ssr

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Errors produced by angular ssr client code, for example error ApolloError: Network error: Http failure response for https://example.com/graphql: 504 Gateway Timeout or variable blahblah is undefined are logged to the node console. Setting logger in NestFactory to false does nothing.

const app = await NestFactory.create<NestExpressApplication>(ApplicationModule, {
    logger: false,
});

Would be nice to disable logging of all errors that come from angular or allowing them to be passed on to a custom logger, ex: sentry, bugsnag, console.log, etc...

Expected behavior

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


Nest version: 6.2.0

 
For Tooling issues:
- Node version: 12.1 
- Platform: 

Others:

Please update concurrently to 5.0.1

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request

Current behavior

There is a transitive prod dependency in this package that is seen as a security vulnerability by some tools. Please update to [email protected] to resolve. I have a PR for this.

Prior art: https://github.com/kimmobrunfeldt/concurrently/issues/204

Before updating (on master):

>npm ls execa --prod
@nestjs/[email protected]
`-- [email protected]
  `-- [email protected]
    `-- [email protected]
      `-- [email protected]  <-- this is the offending package

Expected behavior

>npm ls execa --prod
@nestjs/[email protected]
`-- (empty)

Minimal reproduction of the problem with instructions

npm ls execa --prod

What is the motivation / use case for changing the behavior?

I work in an enterprise which uses SonarQube. This tool has found execa to be security vulnerability when in included in prod dependencies. concurrently is typically meant to be used as a devDependency so if this were the case, my tool would not have a problem here.

Through some light digging and reading the output of npm ls, I found that os-locale (and therefore execa) was removed in a later version of yargs. I submitted the PR to concurrently to use later yargs.

Environment

Any


Nest version: 2.0.1
 
For Tooling issues:
- Node version: 12.13.1 
- Platform:  Windows 
- npm 6.12.1

Client app myapp not found

Hi,

Trying to install your package and getting "Client app myapp not found" while executing the given command inside my brand new angular app.

Angular version : 8.2.14
Angular CLI : 8.3.20

The command line result :

ng-brigolo git:(master) ng add @nestjs/ng-universal --clientProject server    
Installing packages for tooling via npm.
Installed packages for tooling via npm.
Client app server not found.
ng-brigolo git:(master) ✗ ng add @nestjs/ng-universal
Skipping installation: Package already installed
? What is the name of your application? server
Client app server not found.

Angular 9, optimization: true Not Working

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Hi, I'm using Nestjs/ng-universal with Angular 9. If I set the bottom image to "true", there'll be doesn't work. But I do it "false", the app does work. The console screen does not display any errors.

Expected behavior

optimization:true = App Work

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


    "@nestjs/common": "^6.11.8",
    "@nestjs/core": "^6.11.8",
    "@nestjs/ng-universal": "^3.0.1",
    "@nestjs/platform-express": "^6.11.8",
    "@nguniversal/express-engine": "^9.0.0",


problem install into existing project

Bug Report

problem install into existing project

Current behavior

I have an existing project (Angular 8.x.x), when I try to install NestJS I have error problems when typing the name of the app.
My steps are:

  1. I open the project folder
  2. From the terminal, type the command "ng add @ nestjs / ng-universal"
  3. Packages are installed
  4. It asks me the name of the application where I type the exact name and it signals me this error:
    Cannot read property 'kind' of undefined

Input Code

ng add @ nestjs / ng-universal

Environment

Angular 8


Nest version: 6.8.0
Nest Universal 2.0.1
 
For Tooling issues:
- Node version: 10.16.0
- npm 6.9.0
- Platform:  Windows 

Only Use Angular Universal's Server-Side Rendering for Specific Routes

I'm submitting a...

[ ] Regression <!--(a behavior that used to work and stopped working in a new release)-->
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Every route will use sever-side rendering.

Desired behavior

Only certain routes (i.e. not routes that begin with /members) will use server-side rendering.

What is the motivation / use case for the new behavior?

Authorized sections don't gain anything from the SEO benefits of SSR. SSR can also be more work to maintain, which often isn't worth it for member-only areas. It'd be nice to just disable SSR for certain routes/patterns. Perhaps like a blacklist (and/or whitelist)?

I'm using JWT, so I can't really get the initial page load to use authentication, and so with SSR enabled, I basically have to flash my login page before loading the actual content, which isn't a great experience.


Sorry if this can already be done within @nestjs/ng-universal... I couldn't find anything in the docs/code that indicated this was possible, hence the feature request.

Add option to switch to Fastify

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Expected behavior

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Better cold-start times when running in serverless environment

Environment


Nest version: X.Y.Z

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

@nestjs/ng-universal is missing in WebStorms `ng add` integration.

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

@nest/universal doesn't show in WebStorms ng add integration? https://www.youtube.com/watch?v=gd3m8yKPVk8

Expected behavior

I would expect it be available there like other Schematics.

Minimal reproduction of the problem with instructions

Open or generate a new Angular CLI project in WebStorm. Then go to "File > New > Angular Dependency..." and look for nestjs.

Environment


Nest version: 6

For Tooling issues:
- Node version: 12.7 
- Platform:  Mac

Others:
WebStorm 2019.2

Serve different build for desktop and mobile

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

No documentation on the subject

Expected behavior

Would love to see an example on how to serve different versions of an application depending on the device/size.

What is the motivation / use case for changing the behavior?

Imagine having an Angular app for the desktop web and an Ionic app for Android/iOS. It would be beneficial to serve the Ionic version on the web to those that enter it on their phones.

Expose TypeScript Compiler in LiveReloadCompilerOptions

I'm submitting a...


[ ] Regression 
[ ] Bug report
[X] Feature request
[ ] Documentation issue or request
[ ] Support request

Feature proposal

It would be useful to have the ability to override the TypeScript compiler used in LiveReloadCompiler for more flexibility in dev builds.

What is the motivation / use case for changing the behavior?

TypeScript rather painfully does not natively support absolute to relative path mapping, but with ttypescript and ttsc, it is possible to create builds that properly map the dependency paths.

I've implemented an enhancement directly in serve-script.js by copying the contents of LiveReloadCompiler and adapting the code to run outside of a TypeScript environment. It seems to do the trick for my use case. I would submit a PR, but I'm not very well-versed with all the tooling and package management surrounding submitting the enhancement.

const commands = [
  'ng build --aot --watch --delete-output-path=false',
  `${tsCompiler} --watch -p ${tsServerConfigFile}` // Change hard-coded compiler to option
];

Environment

Running serve-script.js via npm run serve.

Nest version: 6.0.0

Returning custom HTTP status codes

I'm submitting a...


[ ] Regression 
[ ] Bug report
[X] Feature request
[X] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

This is my not-found.component.ts:

import { Component, OnInit, Inject, PLATFORM_ID, APP_ID, Optional } from '@angular/core';
import { RESPONSE } from '@nguniversal/express-engine/tokens';
import { Response } from 'express';
import { isPlatformBrowser } from '@angular/common';

@Component({
  selector: 'app-not-found',
  templateUrl: './not-found.component.html',
  styleUrls: ['./not-found.component.scss']
})
export class NotFoundComponent implements OnInit {
  constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
    @Inject(APP_ID) private appId: string,
    @Optional()
    @Inject(RESPONSE)
    private response: Response
  ) {}

  ngOnInit() {
    if (!isPlatformBrowser(this.platformId)) {
      this.response.status(404);
    }
  }
}

and at the end of my app-routing.module.ts route object array:

  { path: '**', component: NotFoundComponent } // Anything else not found goes to 404

Whenever I visit an unknown URL my not found component is rendered with status code 200. Beside that I get the following exception thrown:

ERROR TypeError: Cannot read property 'status' of null
    at NotFoundComponent../src/app/not-found/not-found.component.ts.NotFoundComponent.ngOnInit (C:\Users\h9pe\Documents\project-frontend\frontend\dist\server.js:160073:27)

So how can I return custom HTTP status codes for specific components using nest/ng-universal?

Expected behavior

Returns the not found component and sets the HTTP status code for this response to 404.

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


Nest version: 5.3.10 / Angular 6.1.9

 
For Tooling issues:
- Node version: 10  
- Platform: Windows

@nestjs/ng-universal: 2.0.0 fails with TypeError: provideModuleMap is not a function

[X ] Regression

Current behavior

The old version (1.2.0) works, while the updated one (2.0.0) throws exception in runtime:

[Nest] 120396   - 08/01/2019, 3:27 PM   [ExceptionsHandler] provideModuleMap is not a function +226ms
TypeError: provideModuleMap is not a function
    at View.app.engine (/home/fmike/work/tabius/node_modules/@nestjs/ng-universal/dist/utils/setup-universal.utils.js:23:17)
    at View.render (/home/fmike/work/tabius/node_modules/express/lib/view.js:135:8)
    at tryRender (/home/fmike/work/tabius/node_modules/express/lib/application.js:640:10)
    at Function.render (/home/fmike/work/tabius/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/home/fmike/work/tabius/node_modules/express/lib/response.js:1012:7)
    at app.get (/home/fmike/work/tabius/node_modules/@nestjs/ng-universal/dist/angular-universal.module.js:60:66)
    at Layer.handle [as handle_request] (/home/fmike/work/tabius/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/fmike/work/tabius/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/fmike/work/tabius/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/fmike/work/tabius/node_modules/express/lib/router/layer.js:95:5)

Expected behavior

To work as before

Minimal reproduction of the problem with instructions

Replace 1.2.0 to 2.0.0 in this project:
https://github.com/tabius/tabius

Environment

Linux.

Error after upgrading to nest 6 and ng-universal 0.4.0

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Updated to nest 6 and ng-universal 0.4.0

"@nestjs/common": "^6.0.1",
"@nestjs/core": "^6.0.1",
"@nestjs/ng-universal": "^0.4.0",
"@nestjs/testing": "^6.0.1",
"@nestjs/platform-express": "^6.0.1",

Getting the error below...

###############
[Nest] 7920 - 03/18/2019, 3:58 PM [NestFactory] Starting Nest application...
[Nest] 7920 - 03/18/2019, 3:58 PM [ExceptionHandler] Nest can't resolve dependencies of the AngularUniversalModule (ANGULAR_UNIVERSAL_OPTIONS, ?). Please make sure that the argument at index [1] is available in the AngularUniversalModule context. +22ms
###############

// main.ts
import { enableProdMode } from '@angular/core';
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ApplicationModule } from './app.module';

enableProdMode();

async function bootstrap() {
    const app = await NestFactory.create<NestExpressApplication>(ApplicationModule);

    app.enableCors({
        methods: 'GET',
        maxAge: 3600,
    });

    await app.listen(process.env.PORT);
}

bootstrap().catch(err => console.error(err));
// app.module.ts
import { Module } from '@nestjs/common';
import { AngularUniversalModule } from '@nestjs/ng-universal';
import { join } from 'path';

import { HelmetModule } from './middlewares/helmet.module';
import { SessionModule } from './middlewares/session.module';
import { RoutesController } from './routes/routes.controller';

@Module({
    imports: [
        HelmetModule,
        SessionModule,
        AngularUniversalModule.forRoot({
            viewsPath: join(process.cwd(), 'dist/app'),
            bundle: require('./../dist/server/main.js'),
        }),
    ],
    controllers: [RoutesController],
})
export class ApplicationModule { }

Let me know if you need anything else. Thanks

Use with `@nestjs/pasport` when token invalid will cause "Unhandled Promise rejection Error"

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Use @nestjs/ng-universal with @nestjs/passport together

This is my primary codes:

// app.module.ts
@Module({
  imports: [
    JwtModule.register({
      secret: '123456',
    }),
    PassportModule.register({
      defaultStrategy: 'jwt',
    }),
    AngularUniversalModule.forRoot({
      bundle: require('../server/main'),
      viewsPath: join(process.cwd(), 'dist/browser'),
      liveReload: true,
    }),
  ],
  providers: [
    JwtStrategy,
  ],
  controllers: [
    AppController,
  ],
})
export class ApplicationModule {

}

// jwt.strategy.ts
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {

  constructor() {
    super({
      secretOrKey: '123456',
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
    });
  }

  public async validate(payload: any) {
    return payload;
  }

}

// app.controller.ts
@Controller()
export class AppController {

  @Get()
  @UseGuards(AuthGuard('jwt'))
  public test() {
    return {
      message: 'success',
    };
  }

}

Start this project, and visit test method in controller, this is the error trace:

Unhandled Promise rejection: { statusCode: 401, error: 'Unauthorized' } ; Zone: <root> ; Task: Promise.then ; Value: { Error: [object Object]
    at MixinAuthGuard.handleRequest (/home/hungtcs/Temp/ssr-passport/node_modules/@nestjs/passport/dist/auth.guard.js:63:30)
    at passportFn (/home/hungtcs/Temp/ssr-passport/node_modules/@nestjs/passport/dist/auth.guard.js:47:120)
    at passport.authenticate (/home/hungtcs/Temp/ssr-passport/node_modules/@nestjs/passport/dist/auth.guard.js:78:24)
    at allFailed (/home/hungtcs/Temp/ssr-passport/node_modules/passport/lib/middleware/authenticate.js:107:18)
    at attempt (/home/hungtcs/Temp/ssr-passport/node_modules/passport/lib/middleware/authenticate.js:180:28)
    at JwtStrategy.strategy.fail (/home/hungtcs/Temp/ssr-passport/node_modules/passport/lib/middleware/authenticate.js:297:9)
    at JwtStrategy.authenticate (/home/hungtcs/Temp/ssr-passport/node_modules/passport-jwt/lib/strategy.js:96:21)
    at attempt (/home/hungtcs/Temp/ssr-passport/node_modules/passport/lib/middleware/authenticate.js:361:16)
    at authenticate (/home/hungtcs/Temp/ssr-passport/node_modules/passport/lib/middleware/authenticate.js:362:7)
    at Promise (/home/hungtcs/Temp/ssr-passport/node_modules/@nestjs/passport/dist/auth.guard.js:83:3)
  response: { statusCode: 401, error: 'Unauthorized' },
  status: 401,
  message: { statusCode: 401, error: 'Unauthorized' } } Error: [object Object]
    at MixinAuthGuard.handleRequest (/home/hungtcs/Temp/ssr-passport/node_modules/@nestjs/passport/dist/auth.guard.js:63:30)
    at passportFn (/home/hungtcs/Temp/ssr-passport/node_modules/@nestjs/passport/dist/auth.guard.js:47:120)
    at passport.authenticate (/home/hungtcs/Temp/ssr-passport/node_modules/@nestjs/passport/dist/auth.guard.js:78:24)
    at allFailed (/home/hungtcs/Temp/ssr-passport/node_modules/passport/lib/middleware/authenticate.js:107:18)
    at attempt (/home/hungtcs/Temp/ssr-passport/node_modules/passport/lib/middleware/authenticate.js:180:28)
    at JwtStrategy.strategy.fail (/home/hungtcs/Temp/ssr-passport/node_modules/passport/lib/middleware/authenticate.js:297:9)
    at JwtStrategy.authenticate (/home/hungtcs/Temp/ssr-passport/node_modules/passport-jwt/lib/strategy.js:96:21)
    at attempt (/home/hungtcs/Temp/ssr-passport/node_modules/passport/lib/middleware/authenticate.js:361:16)
    at authenticate (/home/hungtcs/Temp/ssr-passport/node_modules/passport/lib/middleware/authenticate.js:362:7)
    at Promise (/home/hungtcs/Temp/ssr-passport/node_modules/@nestjs/passport/dist/auth.guard.js:83:3)

Expected behavior

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


Nest version: 6.9.0

 
For Tooling issues:
- Node version: v10.16.3  
- Platform:  Linux

Others:

Notes on Upgrading to Angular 8

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Everything works with Angular 7, but if you upgrade your cli and then upgrade the angular universal app:

npm install -g @angular/cli@next
ng update @angular/cli @angular/core codelyzer --next

A couple of problems appear:

  1. Angular complains about the lazy loading of modules unless you change the "compilerOptions"->"module":"esNext" in the tsconfig.app.json file
  2. If you try the SSR build, you get the error already reported here - #64
  3. The SSR build fails, because the ng-universal/webpack-config.factory.js has this section:
test: /\module.ts$/,
                        loader: 'string-replace-loader',
                        options: {
                            search: '../server/main',
                            replace: '../dist/server/main',
                            flags: 'g'
                        }

and apparently in the latest version of string-replace-loader, including any flags in the options turns on regex, and because the periods are in there unescaped, it totally messes the replacement-

Expected behavior

Should work with Angular 8 :)

Minimal reproduction of the problem with instructions

See above

What is the motivation / use case for changing the behavior?

Getting ready for Angular 8!

Environment


Nest version: 6.0.1

 
For Tooling issues:
- Node version: 10.15.3  
- Platform:  Mac

Others:

AngularUniversalModule destroys the route from SwaggerModule and nestjs

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

AngularUnversalModule damages the nestjs route and swagger route

Expected behavior

all routes from AngularUniversalModule, SwaggerModule and nestjs should work properly

Minimal reproduction of the problem with instructions

git clone https://github.com/hwalyonglance/nestjs-nguniversal
cd nestjs-nguniversal
npm install
npm run build:ssr && npm run serve:ssr

then open http://localhost:4000/hello for nestjs REST API or http://localhost:4000/api-docs for Swagger route

What is the motivation / use case for changing the behavior?

Environment


Nest version: 6.1.1

 
For Tooling issues:
```
```

Others:

Module not found: Error: Can't resolve 'pg-native'

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

I have installed @nestjs/typeorm, typeorm and pg packages.

When I run npm compile:server I expect compiling the server folder to the ./dist folder. However, I get the following exceptions on the terminal window:

ERROR in ./node_modules/pg/lib/native/client.js
Module not found: Error: Can't resolve 'pg-native' in '/Users/bilalhaidar/Projects/thisdotmedia/seeding-migration-typeorm/node_modules/pg/lib/native'
 @ ./node_modules/pg/lib/native/client.js 11:13-33
 @ ./node_modules/pg/lib/native/index.js
 @ ./node_modules/pg/lib/index.js
 @ ./node_modules/typeorm/platform/PlatformTools.js
 @ ./node_modules/typeorm/index.js
 @ ./server/src/blog/post.entity.ts
 @ ./server/src/blog/blog.module.ts
 @ ./server/app.module.ts
 @ ./server/main.ts
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] compile:server: `webpack --config webpack.server.config.js --progress --colors`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the [email protected] compile:server script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/bilalhaidar/.npm/_logs/2019-08-25T21_38_35_373Z-debug.log

Expected behavior

The server folder gets compiled inside the ./dist folder

Minimal reproduction of the problem with instructions

https://github.com/bhaidar/seeding-migration-typeorm

Environment


Nest version: 6.6.4

 
For Tooling issues:
- Node version: 10.16.2 
- Platform:  Mac

ReferenceError: window is not defined

Hi, I think I found a bug with this package. I can produce it with the following steps.

Current behavior

After installing ng-universal into an existing project, I got the following error message:

ReferenceError: window is not defined
    at Object.<anonymous> (/Users/niklasravnsborg/Code/angular-nest-nebular/node_modules/intersection-observer/intersection-observer.js:724:3)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at /Users/niklasravnsborg/Code/angular-nest-nebular/node_modules/@nebular/theme/bundles/theme.umd.js:2:469
    at Object.<anonymous> (/Users/niklasravnsborg/Code/angular-nest-nebular/node_modules/@nebular/theme/bundles/theme.umd.js:5:2)
[nodemon] app crashed - waiting for file changes before starting...

I suspect this has something to do with server side rendering but I don't get any error before installing @nestjs/ng-universal, so I would think this is a problem with this package.

Minimal reproduction of the problem with instructions

ng new angular-nest-nebular
cd angular-nest-nebular
ng add @nebular/theme
ng add @nestjs/ng-universal
npm run serve

Or just clone the test repository and run npm i && npm run server:
https://github.com/niklasravnsborg/angular-nest-nebular

Environment

Nest version: 6.0.0
@nestjs/ng-universal: 2.0.1
@nebular/theme: 4.4.0

Please move concurrently to peerDependencies

I'm submitting a...


[x] Feature request

Current behavior

concurrently is a prod "dependency"

Expected behavior

concurrently is a peerDependency

Minimal reproduction of the problem with instructions

npm ls tree-kill --prod

What is the motivation / use case for changing the behavior?

tree-kill is scary by security scanning software, and it is a dependency of concurrently which is causing my project be flagged by a security tool (apologies if this sounds familiar)

Environment

Any

Support "nest add" in monorepo

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Expected behavior

Ref nestjs/nest-cli#415

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


Nest version: X.Y.Z

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

TypeError: Cannot read property 'indexOf' of undefined

I'm getting this error in
ng-universal\dist\utils\setup-universal.utils.js:35:43

just used ng new App -> ng add @nestjs/ng-universal -> npm run serve

I'm submitting a...


[ ] Regression 
[*] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Application does not run, returns 500

Expected behavior

Application runs just fine

Minimal reproduction of the problem with instructions

Created an Angular app, used ng add to add ng-universal

What is the motivation / use case for changing the behavior?

Environment


Nest version: lastest

 
For Tooling issues:
- Node version: 12.14  
- Platform:  Windows

Others:

Support for multiple angular universal apps

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ x] Feature request
[ ] Documentation issue or request

Current behavior

Cannot host two universal apps. Routes are always redirected to last registered app:

imports: [
		AngularUniversalModule.forRoot({
			viewsPath: DIST_BROWSER_FOLDER1,
			bundle: require(join(DIST_BRIDGE_FOLDER1, '/main.js')),
			renderPath: '/path1/*',
			liveReload: true,
		}),
		AngularUniversalModule.forRoot({
			viewsPath: DIST_BROWSER_FOLDER2,
			bundle: require(join(DIST_BRIDGE_FOLDER2, '/main.js')),
			renderPath: '/path2/*',
			liveReload: true,
		}),
	]

Expected behavior

We should be able to handle those two universal apps separatly.

What is the motivation / use case for changing the behavior?

Sometimes we might to host two angular universal app on one server. Without this feature we might need to have two nest servers to handle both of them

Using this with the Mongoose module

I'm submitting a...


[ ] Regression 
[ x] Bug report
[ ] Feature request
[ ] Documentation issue or request

Current behavior

I was attempting to connect a MongoDB instance and had an interesting time tracking down exactly why my app wasn't starting. As soon as I removed the AngularUniversalModule from the AppModule imports... my app started right up.

I spent the better part of the day tracking down what the issue might be to no solution.
I attempted to make the AngularUniversalModule Dynamic and just tossed an await on a timer, however it stops all imports until the timer is over. So I'm obviously not quite as familiar with how this framework works. Maybe I just missed something?

Expected behavior

It seems like this Module needs to load after the Mongo Connection?

Minimal reproduction of the problem with instructions

https://github.com/robstadnick/nest-mongoose (edit: created new repo)
There is a TODO on the app.module.ts above the code to comment out to view issue.
dev - npm run serve
prod - npm run build && npm start

What is the motivation / use case for changing the behavior?

Using this module and the Mongoose module together. Maybe there is a round about solution but it would be great to pass something into the forRoot() or have it instinctively load last?

Environment


Nest version: 6.5.3
- nestjs/ng-universal: 2.0.0
- @nestjs/mongoose: 6.1.2

 
For Tooling issues:
- Node version: 10.16.0  
- Platform:  Mac 
Others:

Error in Angular 8 dynamic import

Transitions and errors occur on pages lazily loaded with dinamyc import.

ERROR { Error: Uncaught (in promise): TypeError: Cannot read property 'call' of undefined
TypeError: Cannot read property 'call' of undefined
    at __webpack_require__ (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:145323:30)
    at Function.requireEnsure [as e] (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:145342:25)
    at ɵ0 (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:145537:38)
    at RouterConfigLoader.loadModuleFactory (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:149667:39)
    at RouterConfigLoader.load (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:149652:35)
    at MergeMapSubscriber.project (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:148655:47)
    at MergeMapSubscriber._tryNext (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:35790:27)
    at MergeMapSubscriber._next (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:35780:18)
    at MergeMapSubscriber.Subscriber.next (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:32339:18)
    at Observable._subscribe (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:34351:24)
    at resolvePromise (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:45498:31)
    at resolvePromise (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:45455:17)
    at /Users/s-mizoguchi/Projects/universal-nest/dist/server.js:45559:17
    at ZoneDelegate.invokeTask (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:45069:31)
    at Object.onInvokeTask (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:27526:33)
    at ZoneDelegate.invokeTask (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:45068:60)
    at Zone.runTask (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:44841:47)
    at drainMicroTaskQueue (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:45247:35)
    at ZoneTask.invokeTask (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:45148:21)
    at Server.ZoneTask.invoke (/Users/s-mizoguchi/Projects/universal-nest/dist/server.js:45133:48)

Update of Angular 8 looks inadequate #66

Is this upgrade guide compatible?

https://github.com/angular/universal/blob/master/docs/v8-upgrade-guide.md

Prerender command fails due to UnhandledPromiseRejectionWarning

I'm submitting a...


[ ] Regression 
[ x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

When I run npm run prerender from a new Angular 9 app, I get the following error:

Prerendering 2 route(s) to /home/john/projects/nwoc/dist/nwoc/browser
(node:28450) UnhandledPromiseRejectionWarning: Error: renderModule method and/or AppServerModule were not exported from: /home/john/projects/nwoc/dist/nwoc/server/main.js.

I cross-compared this Nest-based version of universal to the @nguniversal/express-engine version, and the non-Nest version works and has the same main.server.ts contents.

Expected behavior

Prerender build should work.

Minimal reproduction of the problem with instructions

  1. Create an Angular 9 project from scratch.
  2. $ ng add @nestjs/ng-universal
  3. $ npm run prerender

Configure webconfig file

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[X ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Minimal reproduction of the problem with instructions

Hello guys.
I need help.

I was using @ ng-toolkit / universal. Where does it have a local.js file

I removed him from my project and I'm working with Nest. I did all the build part for production and arresting.
I applied the files generated in dist on the server.

With the toolkit that had a webconfig, pointing the path of the local.js file that read the dist / server folder.

With Nest I found the file server-scripts.js. Putting it on my server and pointing the way the project does not open.

Is there any other webconfig setup to be done? The server is windows.

AngularUniversalModule to serve compressed files from ng build --prod

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

ng build --prod doesn't generate gzipped files and expects the compression to happen server level.

I've tried using the compression package in server.ts and applying it immediately after.

Expected behavior

AngularUniversalModule to serve compressed files from ng build --prod

Minimal reproduction of the problem with instructions

import * as compression from 'compression';
...
const app = await NestFactory.create(AppModule);
app.use(compression());

This works for (some) HTTP requests to the API but never for main.js or any lazy loaded modules.

What is the motivation / use case for changing the behavior?

Reduced bundle size.

Environment


Nest version: ^6.0.0

 
For Tooling issues:
- Node version: v10.15.1
- Platform:  Windows

Others:

Cannot read property 'projectType' of undefined

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Failed during Installation

ng add @nestjs/ng-universal

Angular version

"@angular/animations": "~7.2.0",
"@angular/common": "~7.2.0",
"@angular/compiler": "~7.2.0",
"@angular/core": "~7.2.0",
"@angular/forms": "~7.2.0",
"@angular/platform-browser": "~7.2.0",
"@angular/platform-browser-dynamic": "~7.2.0",
"@angular/router": "~7.2.0",
"@nestjs/ng-universal": "^2.0.1",
"bootstrap": "^3.4.1",
"core-js": "^2.5.4",
"rxjs": "~6.3.3",
"tslib": "^1.10.0",
"zone.js": "~0.8.26"

Environment


Nest version:"^2.0.1"

 
For Tooling issues:
- Node version: XX  
- Platform:  Linux, 

Others:

Cannot read property 'subscribe' of undefined

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Whenever I try to load my Angular Universal project, I get the following error:

TypeError: Cannot read property 'subscribe' of undefined
    at new ApplicationRef (/home/qjnr/Documents/quote-machine/packages/core/src/application_ref.ts:387:33)
    at _createClass (/home/qjnr/Documents/quote-machine/packages/core/src/view/ng_module.ts:186:7)
    at _createProviderInstance (/home/qjnr/Documents/quote-machine/packages/core/src/view/ng_module.ts:144:20)
    at initNgModule (/home/qjnr/Documents/quote-machine/packages/core/src/view/ng_module.ts:74:24)
    at new NgModuleRef_ (/home/qjnr/Documents/quote-machine/packages/core/src/view/refs.ts:496:5)
    at createNgModuleRef (/home/qjnr/Documents/quote-machine/packages/core/src/view/refs.ts:478:10)
    at Object.debugCreateNgModuleRef [as createNgModuleRef] (/home/qjnr/Documents/quote-machine/packages/core/src/view/services.ts:163:10)
    at NgModuleFactory_.create (/home/qjnr/Documents/quote-machine/packages/core/src/view/entrypoint.ts:70:21)
    at /home/qjnr/Documents/packages/core/src/application_ref.ts:231:63
    at ZoneDelegate.invoke (/home/qjnr/Documents/quote-machine/node_modules/zone.js/dist/zone-node.js:391:26)

Expected behavior

It should work.

Minimal reproduction of the problem with instructions

Create an Angular Universal project, and compile it. Then create a Nest.js application and load the AngularUniversal module like the documentation says.

What is the motivation / use case for changing the behavior?

I don't know what to fill in here.

Environment


Nest version: 5.3.7 (`@nestjs/core` module and some others)

 
For Tooling issues:
- Node version: 11.6.0 
- Platform:  Linux (openSUSE Tumbleweed) 

Others:

Related question on StackOverflow

https://stackoverflow.com/q/54425931/8649828

Please publish new version to npm

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request

Current behavior

2.0.1 is latest (from four months ago)

Expected behavior

3.0.0, or 2.1.0, or 2.0.2 is latest

Minimal reproduction of the problem with instructions

https://www.npmjs.com/package/@nestjs/ng-universal

What is the motivation / use case for changing the behavior?

I want the latest dependency changes from this module in my application.

Environment

npm

Enable swagger and swagger-stats

I'm submitting a...


[ ] Regression 
[X] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

When I add swagger and swagger-ui for documentation and statics. It doesn't load work. I get errors on the startup.

Following error was provided:


{ Error: ENOENT: no such file or directory, open '//indexTemplate.html'
    at Object.fs.openSync (fs.js:577:3)
    at Object.fs.readFileSync (fs.js:483:33)
    at Object.generateHTML (/Users/bovandersteene/projects/github/talks/angular-connect/collection/dist/server.js:168517:16)
    at Function.setup (/Users/bovandersteene/projects/github/talks/angular-connect/collection/dist/server.js:168461:39)
    at /Users/bovandersteene/projects/github/talks/angular-connect/collection/dist/server.js:168:83
    at step (/Users/bovandersteene/projects/github/talks/angular-connect/collection/dist/server.js:131:23)
    at Object.next (/Users/bovandersteene/projects/github/talks/angular-connect/collection/dist/server.js:112:53)
    at fulfilled (/Users/bovandersteene/projects/github/talks/angular-connect/collection/dist/server.js:103:58)
    at ZoneDelegate.invoke (/Users/bovandersteene/projects/github/talks/angular-connect/collection/dist/server.js:170788:26)
    at Zone.run (/Users/bovandersteene/projects/github/talks/angular-connect/collection/dist/server.js:170538:43)
  errno: -2,
  syscall: 'open',
  code: 'ENOENT',
  path: '//indexTemplate.html' }

Expected behavior

Access for swagger should be provided

Minimal reproduction of the problem with instructions

Add swagger to your main.ts file


import { NestFactory } from '@nestjs/core';
import { AppModule } from './src/app.module';
import * as swStats from 'swagger-stats';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

import { enableProdMode } from '@angular/core';
enableProdMode();

async function bootstrap() {
  const app = await NestFactory.create(AppModule); 
  app.enableCors({
    methods: 'GET',
    maxAge: 3600,
  });

  const options = new DocumentBuilder()
    .setTitle('My-Collection backend')
    .setDescription('The collection api')
    .setVersion('1.0')
    .addTag('reibo')
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('swagger', app, document);
  app.use(swStats.getMiddleware());

  await app.listen(4000);
}
bootstrap().catch(err => console.error(err));

What is the motivation / use case for changing the behavior?

Environment


Nest version:  5.3.10

 
For Tooling issues:
- Node version: XX  v10.2.1
- Platform:  Mac

Others:

Support for @nestjs/graphql

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

When implementing the @nestjs/graphql package into a project using @nestjs/ng-universal following the provided installation instructions, the webpack command results in errors when building.

Seems to be related to the WebpackConfigFactory and it not being configured to build for this scenario (.mjs file extensions, etc.)

Expected behavior

A basic @kamilmysliwiec/universal-nest starter application can be extended to use @nestjs/graphql without failing to compile

Minimal reproduction of the problem with instructions

You should see this fail when getting to the webpack --config webpack.server.config.js --progress --colors portion of the build.

What is the motivation / use case for changing the behavior?

Integrate @Nestjs/GraphQL with an Angular Universal application running on Nest.js Universal module.

Environment


Nest version: 6.5.2

 
For Tooling issues:
- Node version: v10.16.0  
- Platform:  Mac

Others:

@Inject(REQUEST) not available at angular side

I'm submitting a...

[ ] Regression
[ ] Bug report
[x] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

SSR does not provide the current host for DI.

Expected behavior

"request" should not be null in angular services.

constructor(private http: HttpClient,
              @Optional() @Inject(REQUEST) private request: any,
              @Inject(PLATFORM_ID) private platformId: Object) {
    if (isPlatformServer(this.platformId)) {
      console.log(this.request.get('host')); // host on the server
    } else {
      console.log(document.location.hostname); // host on the browser
    }
  }

What is the motivation / use case for changing the behavior?

Angular needs absolute urls at server side for api calls to the backend.
See: https://angular.io/guide/universal#using-absolute-urls-for-server-requests

express-engine supports this as shown under "Request based Bootstrap":
https://github.com/angular/universal/blob/master/modules/express-engine/README.md

Environment


Nest version: 5.4.0
 
For Tooling issues:
- Node version: 8.9.4
- Platform:  Windows

Others:

Having the ability to compress (gzip or other) the static files

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

I am serving my Angular Universal app from a Heroku server. Heroku itself does not provide compression techniques, so I have to implement them manually. THankfully, this is easy using packages like compression, but when I apply it to my Nest.js app, it works for API calls ("Content-Type: application/json"), I see the "Content-Encoding: gzip" header in the responses, but it does not apply to the Angular built files like vendor.js and etc.

Expected behavior

Have the ability to either turn on a built in compression algorithm using a new options flag, or (more desirable) having the ability to intercept outgoing responses and compress them (or whatever else)

Minimal reproduction of the problem with instructions

Not applicable

What is the motivation / use case for changing the behavior?

Angular Universal is used primary to increase the app performance and reduce the time to the first meaningful/contentful paint. Serving built Angular JS files is an important part of it, and serving them compressed reduces the time drastically.

Environment

Not applicable


Nest version: 6.6.4

 
For Tooling issues:
- Node version: 10.16.3
- Platform:  Windows, but irrelevant

Others:

Module not found: Error: Can't resolve 'string-replace-loader' in...

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

string-replace-loader used in https://github.com/nestjs/ng-universal/blob/3e491cb46c7387651a7f91b597e14a661820f2fb/lib/webpack-config.factory.ts

Expected behavior

string-replace-loader should be a dependency by default?

Minimal reproduction of the problem with instructions

Error can be fixed by yarn add string-replace-loader --dev

What is the motivation / use case for changing the behavior?

Environment

"@nestjs/common": "6.1.1",
"@nestjs/core": "6.1.1",
"@nestjs/ng-universal": "1.0.2",
"@nestjs/platform-express": "6.1.1",
"@nestjs/testing": "6.1.1",
"@nest-middlewares/compression": "6.0.0",
"@nest-middlewares/express-session": "6.0.0",
"@nest-middlewares/helmet": "6.0.0",

Lazy Loading Angular 9 SSR

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[ x ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

In Angular 9 lazy loading does not work.

Expected behavior

How does lazy loading work in Angular 9?

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


Nest version: X.Y.Z

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Need schematics

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

No schematics

Expected behavior

Need Schematics similar to what is mentioned in Angular Universal guide on angular.io https://angular.io/guide/universal

ng add @nguniversal/express-engine --clientProject angular.io-example

we need something like this ng add @nestjs/ng-universal or ng add @nestjs/schematics

ng add @nestjs/ng-universal --clientProject nestjs.com-example --prerender

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


Nest version: X.Y.Z

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Release schedule ?

Hi,

This is just the module I am looking for :-)

Do you know the release schedule, I checked on the release tab but it seems there are currently no releases.

I presume this module is quite new ?

npm warnings when using Angular v7

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

npm i --save @nestjs/ng-universal
npm WARN @nestjs/[email protected] requires a peer of @angular/platform-server@^6.1.8 but none is installed. You must install peer dependencies yourself.
npm WARN @nestjs/[email protected] requires a peer of @nguniversal/common@^6.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN @nestjs/[email protected] requires a peer of @nguniversal/express-engine@^6.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN @nestjs/[email protected] requires a peer of @nguniversal/module-map-ngfactory-loader@^6.1.0 but none is installed. You must install peer dependencies yourself.

Expected behavior

No warnings when installing with Angular v7.

Minimal reproduction of the problem with instructions

Above.

What is the motivation / use case for changing the behavior?

Support the latest stable release of Angular.

Environment


Nest versions:
    "@nestjs/common": "5.4.0",
    "@nestjs/core": "5.4.0",
    "@nestjs/ng-universal": "^0.1.1",

 
For Tooling issues:
- Node version: v8.11.3
- Platform: macOS Mojave

Others:

npm: 6.4.1

Add projectDir option for WebpackConfigFactory.create

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

When using a different angular project structures like Nx Workspace, the src folder could end up being apps/todo/src.

ng-univeral WepbackConfigFactory configues the ContextReplacementPlugin to defaults to src which throws an error in a different angular project.

join(currentDir, 'src'), // location of your src

Expected behavior

The WebpackConfigFactory static method create should recieve a projectDir option to properly configure the ContextReplacementPlugin

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Ability to use ng-universal with other project structures like nx-workspace

Environment


Nest version: X.Y.Z

 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Angular 9 Support

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Running SSR with Angular 9 (9.0.0-rc.4): it seems that AppServerModuleNgFactory has been renamed AppServerModule (ngOptions.bundle)

I tried renaming it to AppServerModule and it worked, it's all it was needed but I am not sure if in reality there's something else to tweak.

Below is a log of the error:

[Nest] 28783   - 11/30/2019, 1:52:33 PM   [NestFactory] Starting Nest application...
[Nest] 28783   - 11/30/2019, 1:52:33 PM   [InstanceLoader] AngularUniversalModule dependencies initialized +12ms
[Nest] 28783   - 11/30/2019, 1:52:33 PM   [InstanceLoader] AppModule dependencies initialized +1ms
[Nest] 28783   - 11/30/2019, 1:52:33 PM   [RoutesResolver] AppController {/api/}: +5ms
[Nest] 28783   - 11/30/2019, 1:52:33 PM   [RouterExplorer] Mapped {/hello, GET} route +2ms
[Nest] 28783   - 11/30/2019, 1:52:33 PM   [NestApplication] Nest application successfully started +2ms
Listening at http://localhost:3333/api
ERROR [NetworkError]
{
  templatePath: '/Users/giancarlo/Lab/project/dist/browser/index.html',
  rootStaticPath: '*.*',
  renderPath: '*',
  viewsPath: '/Users/giancarlo/Lab/project/dist/browser',
  bundle: {
    AppServerModule: [Function: AppServerModule] {
      'ɵmod': [Object],
      'ɵinj': [Object],
      decorators: [Array]
    },
    ngExpressEngine: [Function: ngExpressEngine],
    provideModuleMap: [Function: provideModuleMap]
  },
  liveReload: true

Line I changed:

const { **AppServerModule**, LAZY_MODULE_MAP, provideModuleMap, ngExpressEngine } = ngOptions.bundle;

Expected behavior

Support for Angular 9

Minimal reproduction of the problem with instructions

Install a clean Angular 9 repo with ng-universal, run SSR

What is the motivation / use case for changing the behavior?

Support Angular 9

Environment


Nest version: 6.10.4
Nest ng-Universal: 2.0.1

 
For Tooling issues:
- Node version: v12.4.0
- Platform:  Mac

Others:

Using with NX, error running nodejs ?


[ ] Regression 
[x] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

I am a little confused here and there doesn't seem to be much docs. I have 2 apps configured in NX, one an angular and one the nestjs with SSR

I build both apps (using ng build) and then i get

Error: Cannot find module '/Users/ian/Development/Personal/typescript/ui/dist/apps/api/main.js'
    at webpackEmptyContext (/Users/ian/Development/Personal/typescript/ui/dist/apps/api/webpack:/apps/api/src/app sync:2:1)
    at /Users/ian/Development/Personal/typescript/ui/dist/apps/api/webpack:/apps/api/src/app/app.module.ts:12:15

And my main app.module inside nestjs app i haver

  imports: [
    AngularUniversalModule.forRoot({
      viewsPath: join(process.cwd(), "dist/apps/ui"),
      bundle: require(join(process.cwd(), "dist/apps/api/main.js"))
    })
  ],

I know that the files exist inside the dist folder.

Its not my first time with nestjs or angular but this is really confusing me. There doesn't seme to be any docs as such. I tested the example, and it has a webpack file in the root, i didn;t use that as NX builds my projects (node) i.e from angular.json

    "api": {
      "root": "apps/api",
      "sourceRoot": "apps/api/src",
      "projectType": "application",
      "prefix": "api",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@nrwl/builders:node-build",
          "options": {

So basically I am doing an

ng build api
ng build ui

and then running node dist/apps/api/main.js

but it fails..

Expected behavior

To provide a clear example with an explanation of what each part is doing, would be really nice to comment about the use with NX.

What is the motivation / use case for changing the behavior?

Environment


Nest version: 6.1
 
For Tooling issues:
- Node version: 11
- Platform:  MAC
Others:

Can't resolve

WARNING in ./node_modules/@nestjs/common/utils/load-package.util.js
Module not found: Error: Can't resolve '/src' in 'node_modules/@nestjs/common/utils'
@ ./node_modules/@nestjs/common/utils/load-package.util.js
@ ./node_modules/@nestjs/core/nest-factory.js
@ ./node_modules/@nestjs/core/index.js
@ ./apps/server/src/main.ts

ERROR in ./node_modules/@angular/core/fesm5/core.js
Module not found: Error: Can't resolve '/src' in '/node_modules/@angular/core/fesm5'
@ ./node_modules/@angular/core/fesm5/core.js 18260:15-36 18272:15-102
@ ./node_modules/@nguniversal/module-map-ngfactory-loader/fesm5/module-map-ngfactory-loader.js
@ ./node_modules/@nestjs/ng-universal/dist/utils/setup-universal.utils.js
@ ./node_modules/@nestjs/ng-universal/dist/angular-universal.providers.js
@ ./node_modules/@nestjs/ng-universal/dist/angular-universal.module.js
@ ./node_modules/@nestjs/ng-universal/dist/index.js
@ ./node_modules/@nestjs/ng-universal/index.js
@ ./apps/server/src/app/app.module.ts
@ ./apps/server/src/main.ts

Error when importing Validation Pipe. Use of dynamic require?

I'm submitting a...


[ ] Regression 
[x ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Please see TrilonIO/universal-nest#7

Expected behavior

Minimal reproduction of the problem with instructions

TrilonIO/universal-nest#7

What is the motivation / use case for changing the behavior?

Environment


Nest version: 5.3.7

 
For Tooling issues:
- Node version: 10.x.x  
- Platform:  Linux 

Others:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.