Suppose I want to develop an app using the following commands:
npx create-next-app --typescript example-app
- Create server.ts
- Copy and paste the code from https://www.geeksforgeeks.org/next-js-custom-server/ into server.ts
- Replace all instances of
require()
withimport
- Include
//@ts-nocheck
at the beginning of theserver.ts
file
- Modify tsconfig.json
- Change the "target" to
"target": "ESNext",
- Change the "target" to
- Update package.json
- Revise the "dev" script to
"dev": "npx tsx server.ts",
- Revise the "dev" script to
After executing npm run dev
, an error message appeared:
TypeError: Unexpected response from worker: undefined
at ChildProcessWorker._onMessage (.......\node_modules\next\dist\compiled\jest-worker\index.js:1:12492)
package.json
{
"name": "example-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "npx tsx server.ts",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@types/node": "20.6.2",
"@types/react": "18.2.21",
"@types/react-dom": "18.2.7",
"next": "13.4.19",
"react": "18.2.0",
"react-dom": "18.2.0",
"typescript": "5.2.2"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
server.ts
//@ts-nocheck
// const next = require('next')
// const http = require('http')
import { createServer } from "http";
import next from "next";
const app = next({dev: process.env.NODE_ENV !== 'production'})
app.prepare().then(() => {
const server = createServer((req, res) => {
// Handle API routes
if (req.url.startsWith('/api')) {
// Your API handling logic here
} else {
// Handle Next.js routes
return app.getRequestHandler()(req, res)
}
})
server.listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})