• Stars
    star
    441
  • Rank 98,861 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 6 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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.

More Repositories

1

nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
TypeScript
67,297
star
2

awesome-nestjs

A curated list of awesome things related to NestJS 😎
10,616
star
3

nest-cli

CLI tool for Nest applications 🍹
TypeScript
1,939
star
4

typeorm

TypeORM module for Nest framework (node.js) 🍇
TypeScript
1,906
star
5

typescript-starter

Nest framework TypeScript starter ☕
TypeScript
1,854
star
6

swagger

OpenAPI (Swagger) module for Nest framework (node.js) 🌎
TypeScript
1,671
star
7

graphql

GraphQL (TypeScript) module for Nest framework (node.js) 🍷
TypeScript
1,453
star
8

docs.nestjs.com

The official documentation https://docs.nestjs.com 📕
TypeScript
1,190
star
9

cqrs

A lightweight CQRS module for Nest framework (node.js) 🎈
TypeScript
827
star
10

terminus

Terminus module for Nest framework (node.js) 🤖
TypeScript
668
star
11

throttler

A rate limiting module for NestJS to work with Fastify, Express, GQL, Websockets, and RPC 🧭
TypeScript
619
star
12

bull

Bull module for Nest framework (node.js) 🐮
TypeScript
602
star
13

jwt

JWT utilities module based on the jsonwebtoken package 🔓
TypeScript
599
star
14

mongoose

Mongoose module for Nest framework (node.js) 🍸
TypeScript
520
star
15

config

Configuration module for Nest framework (node.js) 🍓
TypeScript
513
star
16

passport

Passport module for Nest framework (node.js) 🔑
TypeScript
497
star
17

serve-static

Serve static websites (SPA's) using Nest framework (node.js) 🥦
TypeScript
454
star
18

elasticsearch

Elasticsearch module based on the official elasticsearch package 🌿
TypeScript
382
star
19

schematics

Nest architecture element generation based on Angular schematics 🎬
TypeScript
382
star
20

mapped-types

Configuration module for Nest framework (node.js) 🐺
TypeScript
374
star
21

schedule

Schedule module for Nest framework (node.js) ⏰
TypeScript
350
star
22

sequelize

Sequelize module for Nest framework (node.js) 🍈
TypeScript
231
star
23

axios

Axios module for Nest framework (node.js) 🗂
TypeScript
219
star
24

event-emitter

Event Emitter module for Nest framework (node.js) 🦋
TypeScript
193
star
25

serverless-core-deprecated

[Deprecated] Serverless Core module for Nest framework (node.js) 🦊
TypeScript
171
star
26

azure-func-http

Azure Functions HTTP adapter for Nest framework (node.js) 🌥
TypeScript
151
star
27

nestjs.com

The official website https://nestjs.com 🏆
HTML
135
star
28

courses.nestjs.com

Official NestJS Courses website https://courses.nestjs.com 🏡
HTML
126
star
29

cache-manager

Cache manager module for Nest framework (node.js) 🗃
TypeScript
118
star
30

javascript-starter

Nest framework JavaScript (ES6, ES7, ES8) + Babel starter 🍰
JavaScript
117
star
31

azure-database

Azure CosmosDB Database module for Nest framework (node.js) ☁️
TypeScript
105
star
32

azure-storage

Azure Storage module for Nest framework (node.js) ☁️
TypeScript
86
star
33

enterprise.nestjs.com

The official website https://enterprise.nestjs.com 🌁
HTML
18
star
34

newsletter.nestjs.com

Official NestJS Newsletter website https://newsletter.nestjs.com 📩
HTML
12
star