Combining the next framework with a custom server written in TypeScript using the npx command may result

Suppose I want to develop an app using the following commands:

  • npx create-next-app --typescript example-app
  • Create server.ts
  • Modify tsconfig.json
    • Change the "target" to
      "target": "ESNext",
  • Update package.json
    • Revise the "dev" script to
      "dev": "npx tsx server.ts",

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')
})
})

Answer №1

I've encountered the same issue recently while working with tsx. I also experimented with ts-node-dev but faced the same problem.

If your objective is to execute the server process using a TypeScript file, you can consider using ts-node

P.S.

Avoid adding //@ts-nocheck at the beginning of server.ts

Here's the setup that has been effective for me:

// package.json
"scripts": {
    "dev": "ts-node --project tsconfig.server.json server.ts",
    "build:client": "next build",
    "build:server": "tsc --project tsconfig.server.json",
    "build": "pnpm build:server && pnpm build:client",
    "start": "cross-env NODE_ENV=production node dist/server.js",
    "lint": "next lint"
  },
// tsconfig.json

{
  "compilerOptions": {
    "target": "es2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "checkJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "noUncheckedIndexedAccess": true,
    "baseUrl": ".",
    "paths": {
      "$/*": ["./src/*"]
    },
    "plugins": [{ "name": "next" }]
  },
  "include": [
    ".eslintrc.cjs",
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "**/*.cjs",
    "**/*.mjs",
    ".next/types/**/*.ts"
  ],
  "exclude": ["node_modules", "dist", "out"]
}

// tsconfig.server.json

{
  "extends": "./tsconfig.json",
  "include": ["server.ts"],
  "exclude": ["node_modules", "dist", "out"],
  "compilerOptions": {
    "module": "CommonJS",
    "outDir": "./dist",
    "noEmit": false
  },
  "ts-node": {
    "transpileOnly": true,
    "compilerOptions": {
      "module": "CommonJS"
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the transcluded content visible to the class as a whole?

Angular2 makes it simple to create a component like this: @Component({ selector: 'some', properties: ['header'] }) @View({ template: ` <div> <h2>{{ getFormattedHeader() }}</h2> <p><conte ...

Contrasting ./ and $ in React project module imports

The creator of this particular project has utilized a different path to import a component: import { client } from '$lib/graphql-client' I'm curious: What is the significance of the $ symbol in this case? How does it differ from something ...

Tips for crafting a test scenario for input alterations within Angular

Hello there, currently I am working on an application using Angular and TypeScript. Here is a snippet of my template code: <input type="text" placeholder="Search Results" (input)="searchInput($event)"> And here is the TypeScript code for the searc ...

React-Redux button unit test in Vitest encounters failure

I'm struggling with passing a button click test in my app component using Vitest, react-testing-library, and jest dom. As a newcomer to unit testing, I'm having difficulty figuring out how to make my test for the submit button in my form function ...

Issues with Ionic 3 Directive Not Functioning

Struggling to create a custom directive in Ionic that won't resize automatically? I can't figure out what's going wrong. Here's the code snippet from my project, which is an Ionic 3 app with Angular 4: import { Directive, HostListener ...

How can I use the Required utility type in TypeScript for nested properties?

I'm exploring how to utilize the Required keyword to ensure that all members are not optional in TypeScript. I've achieved success with it so far, but I've run into an issue where it doesn't seem to work for nested members of an interfa ...

What strategies can be implemented to maximize the efficiency of Firebase when designing an admin-only page, in order to minimize unnecessary data reads and

Currently, I have established a secure page within our website that is exclusively accessible to administrators. The technology stack being used includes React Next.js and Cloud Firestore for managing data. As the page is loaded, a read operation in Firest ...

How to showcase the data retrieved via BehaviorSubject in Angular

I've been working on retrieving data from an API using a service and passing it to components using BehaviorSubject in order to display it on the screen: Here is the service code snippet: @Injectable({ providedIn: 'root', }) export clas ...

Issue encountered: Component returning nothing error in a Next.js/React application

I'm currently working on creating image slider component using Nextjs/React and Emotion. I thought I had everything set up correctly but unfortunately, I keep encountering this common error... Error: ImageSliderContainer(...): Nothing was returned f ...

Sharing an Angular 2 class instance across components

As a beginner with Angular 2, I'm adapting well so far. However, I've encountered a problem (possibly due to my familiarity with Angular 1) - I need the class "User" to be global and accessible across different components. Currently, I have a Us ...

Guide on organizing the Object into a precise structure in Angular

I am looking to transform the current API response object into a more structured format. Current Output let temp = [ { "imagePath": "", "imageDescription": [ { "language": "en ...

Issue: Incorrect prop type validation - Expected prop `href` to be a `string` or `object` in the component `<Link>`, but received `undefined` instead

I've been struggling to troubleshoot this issue with no luck. In my Next.js project, I'm importing Link like this: import Link from 'next/link'; I only use it 3 times with the href attribute. However, I keep encountering this error mes ...

Tips for reorganizing the files within a directory using Visual Studio Code

Is there a way to reformat an entire project folder at once, rather than just one document? I know that I can use the shortcut key Alt+Shift+F or right click on a document and select Format Document. My projects consist of Typescript files in the Angular ...

What steps should I take to address the numerous errors I am encountering in Atom using the Atom linter tool?

My Atom interface is showing the following errors: {Error running gjslint}(x4) {Error running selective}(x4) Upon checking the errors section, I found the following details: [Linter] Error running selective Error: ENOENT: no such file or directory, open ...

Using variables to replace 'placeholders' in Typescript with string interpolation

Seeking a definitive answer on this matter, I pose the question: In C#, an example of which would be as follows: var text = "blah blah"; var strTest = String.Format("This is a {0}", text); //output: 'This is a blah blah' How can I accomplish t ...

Utilizing @ngrx/router-store in a feature module: A comprehensive guide

The NGRX documentation for Router-Store only showcases an example with .forRoot(). Upon experimenting with .forFeature(), I realized that this static method does not exist. I am interested in defining certain actions and effects to be utilized within my f ...

A guide on showcasing NFTs with Next.js and Solidity

Lately, I have delved into the world of web3 dapp development and am currently working on a NFT marketplace project. Following tutorials using Solidity and web3/ethers, I successfully showcased the NFTs belonging to the connected wallet. Now, my goal is t ...

In order to make Angular function properly, it is crucial that I include app.get("*", [...]); in my server.js file

Recently, I delved into server side JavaScript and embarked on my inaugural project using it. The project entails a command and control server for my own cloud server, operating with angular, Expressjs, and bootstrap. Presently, I am encountering challeng ...

Guide on incorporating a bespoke cordova plugin into your Ionic 4 project

After successfully completing all the necessary steps to create a new Cordova plugin as outlined in the link below: Start android activity from cordova plugin I executed the command cordova plugin ls which returned the following result: com.example.sam ...

Navigating dynamic authorization-dependent content in Next.js using getStaticProps or getServerSideProps

Currently, I am in the process of developing a Next.js application that requires fetching and displaying content based on the user's authorization status. Initially, I opted for using getStaticProps to cache the content during build time. However, I c ...