iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚄

How to Use Express in Next.js API Routes

に公開

I found a small trick to call an Express instance from within Next.js, so I'm making a note of it.

While I think it will rarely be used, there might be cases where you want to call an external application for some reason.

How to do it

Since we want to handle all routing, use a catch-all route like /api/express/[[...props]].ts.

Next, create an instance with express and pass the req and res received by the handler directly.

// /api/express/[[...props]].ts
import { NextApiHandler } from "next"
import express from "express"

const app = express()
app.get('/api/express', function (req, res) {
  return res.send('root')
})

app.get('/api/express/greet', function (req, res) {
  return res.send('hello world')
})

const handler: NextApiHandler = async (req, res) => {
  app(req, res)
}

export default handler

I used express here for clarity, but it should work to some extent with anything where the Request is an IncomingMessage and the Response is an OutgoingMessage, such as the standard Node.js HTTP API.

Incidentally, I was considering whether this could be done with _middleware in next@12, but it seems it's not possible because that runs in a sandboxed environment called the Edge Runtime, where fs and other modules are unavailable.

GitHubで編集を提案

Discussion