티스토리 뷰

[Next.js] Next.js with nestjs

 

우선 Next.js로 프로젝트 생성

npx create-next-app@latest

 

nestjs 수동 설치

# 개발도구 nestjs/cli 설치
npm i -g @nestjs/cli

# 필수 패키지 수동 설치
npm i @nestjs/core @nestjs/common @nestjs/config @nestjs/platform-express rxjs reflect-metadata
npm i -D @types/express cross-env

 

 

 

nestjs 기본 코드 생성

src/server/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './controllers/app.controller.js';
import { AppService } from './services/app.service.js';

@Module({
    imports: [],
    controllers: [AppController],
    providers: [AppService],
})
export class AppModule {}

 

src/server/controllers/api.controller.ts

import { Controller, Get } from '@nestjs/common';
import { AppService } from '../services/app.service.js';

@Controller()
export class ApiController {
    constructor(private readonly appService: AppService) {}

    @Get('/api')
    getApi(): string {
        return this.appService.getHello();
    }
}

 

src/server/services/app.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
    getHello(): string {
        return 'Hello World!';
    }
}

 

src/main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './server/app.module.js';
import { NextServer } from 'next/dist/server/next';
import express, {NextFunction, Request, Response} from 'express';
import next from 'next';
import {ExpressAdapter} from "@nestjs/platform-express";
import http from "http";

async function bootstrap() {

    let appNext: NextServer|null = null;

    const options = 'development' === process.env.NODE_ENV ? { protocol: 'https', dev: true, hostname: "", port: 443 } : { protocol: 'https', hostname: "", port: 443 };

    try {
        appNext = next(options);
    } catch (error) {
        console.error(error);
        throw error;
    }

    try {
        const handle = appNext.getRequestHandler();
        const server = express();

        const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
        app.use((req: Request, res: Response, next: NextFunction) => {
            if (req.url.startsWith('/_next/static')) {
                next();
            } else if (req.url.startsWith('/_next/webpack')) {
                next();
            } else {
                return next();
            }
        });
        app.use((req: Request, res: Response, next: NextFunction) => {
            if (req.path.startsWith("/api")) {
                next();
            } else {
                return handle(req, res);
            }
        });
        await app.init();

        appNext.prepare()
            .then(() => {
                server.set('port', 3000);

                const httpServer = http.createServer(server);
                httpServer.listen(3000);
            })
            .catch((errorAppNext) => {
                console.error(errorAppNext.stack);
                process.exit(1);
            });
    } catch (error) {
        console.error(error);
    }
}

bootstrap();

 

 

tsconfig는 next.js파일 기본으로 사용

tsconfig.json

{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "jsx": "preserve",
    "incremental": true,
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

 

nestjs에 사용할 tsconfig.server.json 별도로 생성

tsconfg.server.json

{
  "compilerOptions": {
    "module": "esnext",
    "moduleResolution": "node",
    "jsx": "react-jsx",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "ES6",
    "lib": ["ES6", "dom", "dom.iterable", "esnext"],
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}

 

package.json에 추가 사항

nestjs는 기본 셋팅이 commonjs로 되어있는데 nextjs는 esm 셋팅이라서 여기에 맞춰 설정한 해주고

디버깅 모드 실행 시 nestjs 디버깅 명령어로 실행하되

위에서 추가한 tsconfig.server.json 파일을 컴파일러 옵션 파일로 지정해준다.

{
  ...
  "type": "module",
  "scripts": {
    "dev": "nest start --path tsconfig.server.json --watch",
    ...
  },
  ...
}

 

이제 프로젝트를 디버깅모드로 실행해보자.

npm run dev

 

http://localhost:3000

 

http://localhost:3000/api

컨트롤에서 라우팅 한 부분은 nestjs로 그 외에 경로는 next.js에서 라우팅한 페이지로 잘 나온다.

'Programming Framework > Next.js' 카테고리의 다른 글

로또뽑기  (0) 2022.03.27
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함