Next.js Integration
This page is the Part.2 of configuration, we will add a middleware in dev-server to receives API from Inspector Component, and call your local IDE/Editor to open the source file from server side. Please make sure you have already added the Inspector Component in your project as Part.1.
In this section, follow the simple setup below to integrate react-dev-inspector
into your Next.js (opens in a new tab) project.
Setup
At first install the package:
npm i -D @react-dev-inspector/middleware
This middleware package just provides a launchEditorMiddleware
,
you need to add it to Custom Server (opens in a new tab) of Next.js,
and update the dev
script in package.json
.
Here provide a example template for your to create a server.mjs
as custom server:
{
...
"scripts": {
"dev": "node server.mjs",
"build": "next build"
}
}
/**
* https://nextjs.org/docs/pages/building-your-application/configuring/custom-server
*/
import { createServer } from 'node:http'
import next from 'next'
import { launchEditorMiddleware } from '@react-dev-inspector/middleware'
const dev = process.env.NODE_ENV !== 'production'
const hostname = process.env.HOST || 'localhost'
const port = process.env.PORT ? Number(process.env.PORT) : 3000
const app = next({
dev,
hostname,
port,
})
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) => {
/**
* middlewares, from top to bottom
*/
const middlewares = [
/** `react-dev-inspector` server config for nextjs */
launchEditorMiddleware,
/** Next.js default app handler as middleware */
(req, res) => handle(req, res),
]
const middlewarePipeline = middlewares.reduceRight(
(next, middleware) => (
() => { middleware(req, res, next) }
),
() => {},
)
try {
middlewarePipeline()
}
catch (err) {
console.error('Error occurred handling', req.url, err)
res.statusCode = 500
res.end('internal server error')
}
})
.once('error', (err) => {
console.error(err)
process.exit(1)
})
.listen(port, () => {
console.debug(`\n > Ready on http://${hostname}:${port} \n`)
})
That is because the
launchEditorMiddleware
can it CANNOT running in Next.js Edge Runtime (opens in a new tab), that need you to use it in the Custom Server.
Example
Example project code you can find in examples/nextjs-custom-server (opens in a new tab), or see online demo via: