All Projects → kyle-mccarthy → Nest Next

kyle-mccarthy / Nest Next

Licence: mit
Render Module to add Nextjs support for Nestjs

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Nest Next

Nestpress
A production ready personal blogging system on top of NestJS and NEXT.js
Stars: ✭ 38 (-89.08%)
Mutual labels:  nextjs, nestjs
Leaa
Leaa is a monorepo restful CMS / Admin built with Nest.js (@nestjsx/crud, node.js) and Ant Design.
Stars: ✭ 375 (+7.76%)
Mutual labels:  nextjs, nestjs
Ark
An easiest authentication system on top of NestJS, TypeORM, NEXT.js(v9.3) and Material UI(v4).
Stars: ✭ 228 (-34.48%)
Mutual labels:  nextjs, nestjs
Ravepro
RavePro
Stars: ✭ 18 (-94.83%)
Mutual labels:  nextjs, nestjs
Node Blog
🔥✨ A react blog project base on nodejs, nestjs, mongoose, typescript, react, ant-design,nextjs
Stars: ✭ 69 (-80.17%)
Mutual labels:  nextjs, nestjs
Wipi
nextjs + nestjs + TypeScript +MySQL 开发的前后端分离,服务端渲染的博客系统
Stars: ✭ 163 (-53.16%)
Mutual labels:  nextjs, nestjs
Wipi
A blog system written by next.js, nest.js and MySQL.
Stars: ✭ 251 (-27.87%)
Mutual labels:  nextjs, nestjs
Jamstackthemes
A list of themes and starters for JAMstack sites.
Stars: ✭ 298 (-14.37%)
Mutual labels:  nextjs
Nextjs Tailwind Ionic Capacitor Starter
A starting point for building an iOS, Android, and Progressive Web App with Tailwind CSS, React w/ Next.js, Ionic Framework, and Capacitor
Stars: ✭ 315 (-9.48%)
Mutual labels:  nextjs
Devii
A developer blog starter for 2020 (Next.js + React + TypeScript + Markdown + syntax highlighting)
Stars: ✭ 296 (-14.94%)
Mutual labels:  nextjs
Graphcms Examples
Example projects to help you get started with GraphCMS
Stars: ✭ 295 (-15.23%)
Mutual labels:  nextjs
Nest Angular
NestJS, Angular 6, Server Side Rendering (Angular Universal), GraphQL, JWT (JSON Web Tokens) and Facebook/Twitter/Google Authentication, Mongoose, MongoDB, Webpack, TypeScript
Stars: ✭ 307 (-11.78%)
Mutual labels:  nestjs
Nestjs Query
Easy CRUD for GraphQL.
Stars: ✭ 325 (-6.61%)
Mutual labels:  nestjs
Covid19 Brazil Api
API com dados atualizados sobre o status do COVID-19 🦠
Stars: ✭ 300 (-13.79%)
Mutual labels:  nextjs
Woo Next
🚀 React WooCommerce theme, built with Next JS, Webpack, Babel, Node, Express, using GraphQL and Apollo Client
Stars: ✭ 342 (-1.72%)
Mutual labels:  nextjs
Jianshu
仿简书nx+nodejs+nestjs6+express+mongodb+angular8+爬虫
Stars: ✭ 296 (-14.94%)
Mutual labels:  nestjs
Trpc
🧙‍♂️ TypeScript toolkit for building end-to-end typesafe APIs
Stars: ✭ 259 (-25.57%)
Mutual labels:  nextjs
Next.js Typescript Starter Kit
🌳 [email protected], Styled-jsx, TypeScript, Jest, SEO
Stars: ✭ 342 (-1.72%)
Mutual labels:  nextjs
Heroku Nextjs
⏩ Deploy Next.js universal web apps to Heroku
Stars: ✭ 323 (-7.18%)
Mutual labels:  nextjs
Commerce
Next.js Commerce
Stars: ✭ 4,989 (+1333.62%)
Mutual labels:  nextjs

Nest-Next

Render Module to add Nextjs support for Nestjs.

npm PRs Welcome GitHub license

nest-next provides a nestjs module to integrate next.js into a nest.js application, it allows the rendering of next.js pages via nestjs controllers and providing initial props to the page as well.

Table of Contents

Installation

yarn add nest-next

# or

npm install nest-next

Peer Dependencies

  • react
  • react-dom
  • next

if you are using next.js with typescript which most likely is the case, you will need to also install the typescript types for react and react-dom.

Usage

Import the RenderModule into your application's root module and call the forRootAsync method.

import { Module } from '@nestjs/common';
import Next from 'next';
import { RenderModule } from 'nest-next';

@Module({
  imports: [
    RenderModule.forRootAsync(Next({ dev: process.env.NODE_ENV !== 'production' })),
    ...
  ],
  ...
})
export class AppModule {}

Configuration

The RenderModule accepts configuration options as the second argument in the forRootAsync method.

interface RenderOptions {
  viewsDir: null | string;
  dev: boolean;
}

Views/Pages Folder

By default the the renderer will serve pages from the /pages/views dir. Due to limitations with Next, the /pages directory is not configurable, but the directory within the /pages directory is configurable.

The viewsDir option determines the folder inside of pages to render from. By default the value is /views but this can be changed or set to null to render from the root of pages.

Dev Mode

By default the dev mode will be set to true unless the option is overwritten. Currently the dev mode determines how the errors should be serialized before being sent to next.

tsconfig.json

Next 9 added built-in zero-config typescript support. This change is great in general, but next requires specific settings in the tsconfig which are incompatible with what are needed for the server. However, these settings can easily be overridden in the tsconfig.server.json file.

If you are having issues with unexpected tokens, files not emitting when building for production, warnings about allowJs and declaration not being used together, and other typescript related errors; see the tsconfig.server.json file in the example project for the full config.

Rendering Pages

The RenderModule overrides the Express/Fastify render. To render a page in your controller import the Render decorator from @nestjs/common and add it to the method that will render the page. The path for the page is relative to the /pages directory.

import {
  Controller,
  Get,
  Render,
} from '@nestjs/common';

@Controller()
export class AppController {

  @Get()
  @Render('Index')
  public index() {
    // initial props
    return {
      title: 'Next with Nest',
    };
  }
}

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

@Controller()
export class AppController {

  @Get()
  public index(@Res() res: RenderableResponse) {
    res.render('Index', {
      title: 'Next with Nest',
    });
  }
}

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

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

Rendering the initial props

The initial props sent to the next.js view page can be accessed from the context's query method inside the getInitialProps method.

import { NextPage, NextPageContext } from 'next'

// The component's props type
type PageProps = {
  title: string
}

// extending the default next context type
type PageContext = NextPageContext & {
  query: PageProps
}

// react component
const Page: NextPage<PageProps> = ({ title }) => {
  return (
    <div>
      <h1>{title}</h1>
    </div>
  )
}

// assigning the initial props to the component's props
Page.getInitialProps = (ctx: PageContext) => {
  return {
    title: ctx.query.title,
  }
}

export default Page

Handling Errors

By default, errors will be handled and rendered with next's error renderer, which uses the customizable _error page. Additionally, errors can be intercepted by setting your own error handler.

Custom error handler

A custom error handler can be set to override or enhance the default behavior. This can be used for things such as logging the error or rendering a different response.

In your custom error handler you have the option of just intercepting and inspecting the error, or sending your own response. If a response is sent from the error handler, the request is considered done and the error won't be forwarded to next's error renderer. If a response is not sent in the error handler, after the handler returns the error is forwarded to the error renderer. See the request flow below for visual explanation.

ErrorHandler Typedef
export type ErrorHandler = (
  err: any,
  req: any,
  res: any,
  pathname: any,
  query: ParsedUrlQuery,
) => Promise<any>;
Setting ErrorHandler

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

// in main.ts file after registering the RenderModule

const main() => {
  ...

  // get the RenderService
  const service = server.get(RenderService);

  service.setErrorHandler(async (err, req, res) => {
    // send JSON response
    res.send(err.response);
  });

  ...
}

Error Flow (Diagram)

The image is linked to a larger version

error filter sequence diagram

Examples folder structure

Fully setup projects can be viewed in the examples folder

Basic Setup

Next renders pages from the pages directory. The Nest source code can remain in the default /src folder

/src
  /main.ts
  /app.module.ts
  /app.controller.ts
/pages
  /views
    /Index.jsx
/components
  ...
babel.config.js
next.config.js
nodemon.json
tsconfig.json
tsconfig.server.json

Monorepo

Next renders pages from the pages directory in the "ui" subproject. The Nest project is in the "server" folder. In order to make the properties type safe between the "ui" and "server" projects, there is a folder called "dto" outside of both projects. Changes in it during "dev" runs trigger recompilation of both projects.

/server
  /src
    /main.ts
    /app.module.ts
    /app.controller.ts
  nodemon.json
  tsconfig.json
  ...
/ui
  /pages
    /index.tsx
    /about.tsx
  next-env.d.ts
  tsconfig.json
  ...
/dto
  /src
    /AboutPage.ts
    /IndexPage.ts
  package.json

To run this project, the "ui" and "server" project must be built, in any order. The "dto" project will be implicitly built by the "server" project. After both of those builds, the "server" project can be started in either dev or production mode.

It is important that "ui" references to "dto" refer to the TypeScript files (.ts files in the "src" folder), and NOT the declaration files (.d.ts files in the "dist" folder), due to how Next not being compiled in the same fashion as the server.

Versioning

The major version of nest-next corresponds to the major version of next.

License

MIT License

Copyright (c) 2018-present Kyle McCarthy

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].