nesxt
TypeScript icon, indicating that this package has built-in type declarations

9.5.3 • Public • Published

Nesxt

A Next.js Integration Module for NestJS

NPM Version Package License NPM Downloads

Overview

Nesxt is a integration module that overrides the default render method of NestJS by implementing Next.js under the hood, as an template engine, allowing you to render reactive interfaces on demand. Hence, every technique for using the MVVM (Model-View-ViewModel) pattern in React will be seamless integrated and available to Nest.

Features

  • A per-page basis routing system
  • Pre-rendering, both static generation (SSG) and server-side rendering (SSR)
  • Extendable API endpoints
  • Static Files Serving
  • Automatic Code Splitting and Lazy Loading
  • Client-side routing with optimised prefetching
  • Built-in CSS and Sass support, and support for any CSS-in-JS library
  • Custom Error Handlers
  • Development environment which supports Hot Module Replacement
  • Cross-Platform Support

Summary


Installation

$ yarn add nesxt

Examples

See full examples here.

Usage

Setup

Simply import NesxtModule in your Nest application.

import { Module } from "@nestjs/common";
import { NesxtModule } from "nesxt";
 
@Module({
  imports: [
    NesxtModule.forRootAsync(),
    ...
  ],
  ....
})
export class AppModule {}

API Spec

The forRootAsync() method takes an options object with some useful properties.

Property Type Description
viewsDir null/string Views directory, relative to pages dir. Default: "views"
dev boolean Setup the development environment. Default: "true"
rootPath string Static files root directory. Default: "public"
serveRoot string Root path under which static app will be served. Default: ""
renderPath string/RegExp Path to static files (concat with the serveRoot). Default: *
exclude string[] Paths to exclude when serving static files.
serveStaticOptions Object Serve static options (static files)

Rendering Pages

The NesxtModule overrides the Express/Fastify render. However, to make things easier, we introduce the @Router decorator, that can be imported from nesxt and add it to the method that will render the page. The path for the page is relative to the /pages directory. This is useful to keep your routes and controllers in separated files.

import { Router, Get, Render } from "nesxt";
 
@Router()
export class AppRouter {
  @Get()
  @Render("Home")
  public getIndex() {
    // initial props
    return {};
  }
}

Additionally, the render function is made available on the res object.

import { Router, Get, Res, RenderableResponse } from "nesxt";
 
@Router()
export class AppRouter {
  @Get("/")
  public getIndex(@Res() res: RenderableResponse) {
    return res.render("Home");
  }
}

The render function takes in the view, as well as the initial props passed to the page.

render = (view: string, initialProps?: any) => any;

Handling Errors

By default, errors will be handled by next's, which uses the (customizable) _error page.

Custom error handler

A custom error handler can be set to override or enhance it's default behavior.

ErrorHandler Typedef

export type ErrorHandler = (
  errany,
  reqany,
  resany,
  pathnameany,
  queryParsedUrlQuery,
) => Promise<any>;

Setting ErrorHandler

You can set the error handler by getting the NesxtModule from nest's container.

// in main.ts file after registering the NesxtModule
 
const bootstrap() => {
  ...
 
  // get the NesxtService
  const service = server.get(NesxtService);
 
  service.setErrorHandler(async (err, req, res) => {
    // send JSON response
    res.send(err.response);
  });
 
  ...
}
 

Advanced Usage

Passing server data to the Next.js client.

src/app.router.ts

@Router()
export class AppRouter {
  constructor(private readonly app: AppService) {}
 
  @Get("/")
  @Render("Home")
  public getIndex() {
    const { title, content } = await this.app.findAll();
    return { title, content };
  }
}

pages/views/Home.tsx

import React from "react";
import { NextPageContext } from "next";
 
const Home = ({ title, content }) => {
  return (
    <div>
      <h1>{title}</h1>
      <p>{content}</p>
    </div>
  );
};
 
Home.getInitialProps = async ({ query }: NextPageContext) => {
  const { title, content } = query;
  return { title, content };
};
 
export default Home;

Configuration

Update your typescript settings to support the Nesxt environment.

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "emitDecoratorMetadata": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "lib": ["dom", "dom.iterable", "esnext"],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strict": false,
    "target": "es5",
    "baseUrl": "."
  },
  "exclude": ["node_modules"],
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}

tsconfig.build.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "declaration": true,
    "incremental": true,
    "module": "commonjs",
    "noEmit": false,
    "outDir": "dist",
    "removeComments": true,
    "sourceMap": true,
    "target": "es2017"
  },
  "exclude": ["node_modules", "test", "**/*spec.ts"],
  "include": ["src"]
}

Versioning

The major version of nesxt corresponds to the major version of next.

Contributing

Thank you for being interested on making this package better. We encourage everyone to help improving this project with some new features, bug fixes and performance issues. Please take a little bit of your time to read our guides, so this process can be faster and easier.

Contribution Guidelines

Take a moment to read about our Contribution Guidelines so you can understand how to submit an issue, commit and create pull requests.

Code of Conduct

We expect you to follow our Code of Conduct. You can read it to understand what kind of behaviour will and will not be tolerated.

Stay in touch

License

Nesxt is MIT licensed.

Package Sidebar

Install

npm i nesxt

Weekly Downloads

0

Version

9.5.3

License

MIT

Unpacked Size

233 kB

Total Files

61

Last publish

Collaborators

  • costamauri