Skip to content

Instantly share code, notes, and snippets.

@thisismydesign
Last active January 8, 2024 06:57
Show Gist options
  • Save thisismydesign/5149d84580a9decc4a6fe8c042735f88 to your computer and use it in GitHub Desktop.
Save thisismydesign/5149d84580a9decc4a6fe8c042735f88 to your computer and use it in GitHub Desktop.
NestJS + Next.js /2 View Module
import { Controller, Get, Res, Req } from '@nestjs/common';
import { Request, Response } from 'express';
import { parse } from 'url';
import { ViewService } from './view.service';
@Controller('/')
export class ViewController {
constructor(private viewService: ViewService) {}
@Get('home')
public async showHome(@Req() req: Request, @Res() res: Response) {
await this.viewService.handler(req, res);
}
@Get('_next*')
public async assets(@Req() req: Request, @Res() res: Response) {
await this.viewService.handler(req, res);
}
@Get('favicon.ico')
public async favicon(@Req() req: Request, @Res() res: Response) {
await this.viewService.handler(req, res);
}
}
import { Module } from '@nestjs/common';
import { ViewController } from './view.controller';
import { ViewService } from './view.service';
@Module({
imports: [],
providers: [ViewService],
controllers: [ViewController],
})
export class ViewModule {}
import { Injectable, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import createServer from 'next';
import { NextServer } from 'next/dist/server/next';
import { Request, Response } from 'express';
@Injectable()
export class ViewService implements OnModuleInit {
private server: NextServer;
constructor(private configService: ConfigService) {}
async onModuleInit(): Promise<void> {
try {
this.server = createServer({
dev: this.configService.get<string>('NODE_ENV') !== 'production',
dir: './src/client',
});
await this.server.prepare();
} catch (error) {
console.error(error);
}
}
handler(req: Request, res: Response) {
return this.server.getRequestHandler()(req, res);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment