Next.js BFF for Proxy + SSR
server/index.tsにサーバーのコードを書く
code:server/index.ts
import * as express from 'express';
import * as next from 'next';
import * as proxy from 'http-proxy-middleware';
import { IncomingMessage, ServerResponse } from 'http';
const dev = process.env.NODE_ENV !== 'production';
const PORT = process.env.PORT || 8000;
const app = next({ dir: '.', dev });
const handle = app.getRequestHandler();
const main = async () => {
await app.prepare();
const server = express();
server.use('/api', proxy({ target: API_URL }));
server.get('*', (req: IncomingMessage, res: ServerResponse) => handle(req, res));
server.listen(PORT, (err: Error) => {
if (err) throw err;
});
};
main();
開発環境
code:package.json
{
"scripts": {
...
"start": "ts-node server/index.ts",
...
}
}
本番環境デプロイ
code:tsconfig.json
{
"compilerOptions": {
"target": "es2017",
"outDir": "../dist/server",
"declaration": false,
"module": "commonjs",
"noEmit": false,
... // その他必要な設定
}
}
code:package.json
{
"scripts": {
...
// サーバーのビルド
"build": "next build && tsc -p server",
"start": "NODE_ENV=production node dist/server/index.js",
// フロントエンドのビルド
"expoort": "next export"
}
}
非常に参考になった