├── .babelrc ├── .gitignore ├── README.md ├── next-env.d.ts ├── package.json ├── src ├── backend │ ├── app │ │ ├── app.controller.ts │ │ └── app.module.ts │ └── main.ts ├── pages │ ├── api │ │ └── [...catchAll].ts │ ├── gssp.tsx │ └── index.tsx └── public │ ├── favicon.ico │ └── zeit.svg ├── tsconfig.json └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "next/babel", 5 | { 6 | "preset-typescript": { 7 | "onlyRemoveTypeImports": true 8 | } 9 | } 10 | ] 11 | ], 12 | "plugins": [ 13 | "babel-plugin-transform-typescript-metadata", 14 | ["@babel/plugin-proposal-decorators", { "legacy": true }], 15 | "babel-plugin-parameter-decorator" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | 21 | # debug 22 | npm-debug.log* 23 | yarn-debug.log* 24 | yarn-error.log* 25 | 26 | # local env files 27 | .env.local 28 | .env.development.local 29 | .env.test.local 30 | .env.production.local 31 | 32 | .now -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Integrating Next.js and NestJS 2 | 3 | ## Foreword 4 | 5 | While working on [hilfehub.org](https://hilfehub.org), I got to know [Next.js](https://nextjs.org/) and found it to be really great. 6 | Especially the integration of API routes is a very nice feature to have - and having worked using multi-service architectures in the past, I found it a joy to be working on a single monolith. 7 | So I decided to make an effort to migrate [EntE](https://ente.app) (my biggest project to date) to use Next.js. 8 | Having a monolith will hopefully decrease deployment and development complexity - at the moment, theres just a lot going on in the EntE repository. 9 | 10 | ## The Problem 11 | 12 | I've got a fully-working NestJS-based backend, which I don't want to throw away just to migrate to Next.js. 13 | So the goal is to hook up Next.js' API mechanism to my existing backend. 14 | 15 | Since defining a [Custom Server](https://nextjs.org/docs/advanced-features/custom-server) is discouraged in Next.js' docs, I wanted to find a way around doing that. 16 | In this example, we'll make use of [Dynamic API Routes](https://nextjs.org/docs/api-routes/dynamic-api-routes). 17 | We'll define a Catch-All-Route and forward incoming requests to our NestJS instance. 18 | 19 | That's done by creating a file called `/api/[...catchAll].ts`, which - surprise - will catch all requests to `/api`. 20 | In Next.JS, API routes look like this: 21 | 22 | ```ts 23 | export default async (request, response) => { 24 | // do something with `request` and `response`` 25 | response.status(200).send("Hello World"); 26 | } 27 | ``` 28 | 29 | That's basically the interface of Node's `http.Server` Handlers, and since NestJS uses Express internally, which uses http.Server internally, there surely is a away to integrate that with NestJS, right? 30 | Turns out: there is! 31 | 32 | On a high level, this is what we're going to do: We'll get the request handler from our NestJS application and pass our `request` and `response` into it. 33 | 34 | ```ts 35 | async function getNestJSRequestHandler() { 36 | // I will init the NestJS application, 37 | // get the `http.Server` it's running 38 | // and return the registered request handler. 39 | } 40 | 41 | export default async (request, response) => { 42 | const handler = await getNestJSRequestHandler(); 43 | handler(request, response); 44 | } 45 | ``` 46 | 47 | So let's have a look at how that's done. 48 | 49 | ### 1. Init the NestJS application 50 | 51 | Initializing the NestJS app is the easiest part: 52 | 53 | ```ts 54 | const app = await NestFactory.create(AppModule); 55 | 56 | // because our routes are served under `/api` 57 | app.setGlobalPrefix("api") 58 | 59 | await app.init(); 60 | ``` 61 | 62 | ### 2. Get the `http.Server` 63 | 64 | Now we need to get the app's integrated `http.Server`. 65 | NestJS is kind to us - there's a function for it! 66 | 67 | ```ts 68 | const server: http.Server = app.getHttpServer(); 69 | ``` 70 | 71 | ### 3. Get the registered request handler 72 | 73 | This is the hardest part - but with the help of StackOverflow, I found out how to do it. 74 | On `http.Server`, there's the `listeners` function. 75 | It will return you an array of registered handlers. 76 | In our case, there's exactly one, and that's the one we're looking for! 77 | 78 | ```ts 79 | const [ requestHandler ] = server.listeners("request") as NextApiHandler[]; 80 | ``` 81 | 82 | So now we've got our request handler. 83 | Let's get back to our Next.js API route and finish integration. 84 | 85 | ## Finishing touches on our catch-all route 86 | 87 | Although the method above is functioning, you'll see a warning: 88 | 89 | > API resolved without sending a response for /api/, this may result in stalled requests. 90 | 91 | That's because our catch-all handler finishes execution before the request is fully answered. 92 | In reality, all requests are answered, so that warning is a false positive, but let's fix it nevertheless. 93 | 94 | ```ts 95 | export default (request, response) => new Promise( 96 | async resolve => { 97 | const listener = await getNestJSRequestHandler(); 98 | listener(request, response); 99 | response.on("finish", resolve); 100 | } 101 | ); 102 | ``` 103 | 104 | By not using `async` / `await` Syntax but a plain old Promise instead, we can customize when the handler resolves. 105 | Our request is finished once `response` emits the [`finish` event](https://nodejs.org/api/http.html#http_event_finish), 106 | so that's when we'll resolve our handler. 107 | 108 | ## Conclusion 109 | 110 | Integrating Next.js and NestJS is easier than it seems - and by using this strategy, you can basically connect every `http.Server`-based framework to Next.js. 111 | If you want to see a working example, have a look at the code in this repo, which you can see in action [here](https://nextjs-nestjs-integration-example.simonknott.de). 112 | -------------------------------------------------------------------------------- /next-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nextjs-nestjs-migration-example", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev", 7 | "build": "next build", 8 | "start": "next start" 9 | }, 10 | "dependencies": { 11 | "@nestjs/common": "^7.0.7", 12 | "@nestjs/core": "^7.0.7", 13 | "@nestjs/platform-express": "^7.0.7", 14 | "next": "^10.0.1", 15 | "react": "16.13.1", 16 | "react-dom": "16.13.1", 17 | "rxjs": "^6.5.5" 18 | }, 19 | "devDependencies": { 20 | "@babel/core": "^7.13.13", 21 | "@babel/plugin-proposal-decorators": "^7.8.3", 22 | "@types/node": "^13.11.1", 23 | "@types/react": "^16.9.34", 24 | "babel-plugin-parameter-decorator": "^1.0.16", 25 | "babel-plugin-transform-typescript-metadata": "^0.3.2", 26 | "reflect-metadata": "^0.1.13", 27 | "ts-node": "^8.8.2", 28 | "typescript": "^4.2.4" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/backend/app/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Param } from "@nestjs/common"; 2 | 3 | @Controller("randomNumber") 4 | export class AppController { 5 | @Get() 6 | randomNumber() { 7 | return Math.random() * 100; 8 | } 9 | 10 | @Get("/:number") 11 | async findOne(@Param("number") param: string) { 12 | return { param }; // You don't even need a return, I put it just to have some return. 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/backend/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from "@nestjs/common"; 2 | import { AppController } from "./app.controller"; 3 | 4 | @Module({ 5 | controllers: [AppController] 6 | }) 7 | export class AppModule {} -------------------------------------------------------------------------------- /src/backend/main.ts: -------------------------------------------------------------------------------- 1 | import "reflect-metadata"; 2 | import { NestFactory } from "@nestjs/core"; 3 | import { AppModule } from "./app/app.module"; 4 | import * as http from "http"; 5 | import { NextApiHandler } from "next"; 6 | import { INestApplication } from "@nestjs/common"; 7 | 8 | export module Backend { 9 | 10 | let app: INestApplication; 11 | 12 | export async function getApp() { 13 | if (!app) { 14 | app = await NestFactory.create( 15 | AppModule, 16 | { bodyParser: false } 17 | ); 18 | app.setGlobalPrefix("api"); 19 | 20 | await app.init(); 21 | } 22 | 23 | return app; 24 | } 25 | 26 | export async function getListener() { 27 | const app = await getApp(); 28 | const server: http.Server = app.getHttpServer(); 29 | const [ listener ] = server.listeners("request") as NextApiHandler[]; 30 | return listener; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/pages/api/[...catchAll].ts: -------------------------------------------------------------------------------- 1 | import { Backend } from "../../backend/main"; 2 | import { NextApiRequest, NextApiResponse } from "next"; 3 | 4 | export default (req: NextApiRequest, res: NextApiResponse) => new Promise(async resolve => { 5 | const listener = await Backend.getListener(); 6 | listener(req, res); 7 | res.on("finish", resolve); 8 | }) -------------------------------------------------------------------------------- /src/pages/gssp.tsx: -------------------------------------------------------------------------------- 1 | import { InferGetServerSidePropsType } from "next"; 2 | import { AppController } from "../backend/app/app.controller"; 3 | import { Backend } from "../backend/main"; 4 | 5 | export async function getServerSideProps() { 6 | const app = await Backend.getApp(); 7 | 8 | const controller = app.get(AppController); 9 | 10 | return { 11 | props: { 12 | randomNumber: controller.randomNumber() 13 | } 14 | } 15 | } 16 | 17 | export default function GsspExample(props: InferGetServerSidePropsType) { 18 | return ( 19 |

20 | Random Number: {props.randomNumber} 21 |

22 | ) 23 | } 24 | -------------------------------------------------------------------------------- /src/pages/index.tsx: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from "react"; 2 | 3 | function useRandomNumber() { 4 | const [ number, setNumber ] = useState(); 5 | 6 | useEffect( 7 | () => { 8 | fetch("/api/randomNumber") 9 | .then(response => response.text()) 10 | .then(text => setNumber(+text)); 11 | }, 12 | [] 13 | ); 14 | 15 | return number; 16 | } 17 | 18 | const Home = () => { 19 | const number = useRandomNumber(); 20 | return ( 21 |

22 | Random Number: {number} 23 |

24 | ) 25 | }; 26 | 27 | export default Home 28 | -------------------------------------------------------------------------------- /src/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Skn0tt/nextjs-nestjs-integration-example/97b25d82bddbdc02bc11ba0df580b0294e379d23/src/public/favicon.ico -------------------------------------------------------------------------------- /src/public/zeit.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "strict": false, 12 | "forceConsistentCasingInFileNames": true, 13 | "noEmit": true, 14 | "esModuleInterop": true, 15 | "module": "esnext", 16 | "moduleResolution": "node", 17 | "resolveJsonModule": true, 18 | "isolatedModules": true, 19 | "jsx": "preserve", 20 | "experimentalDecorators": true, 21 | "emitDecoratorMetadata": true 22 | }, 23 | "exclude": [ 24 | "node_modules" 25 | ], 26 | "include": [ 27 | "next-env.d.ts", 28 | "**/*.ts", 29 | "**/*.tsx" 30 | ] 31 | } 32 | --------------------------------------------------------------------------------