DEV Community

Andrei Canta
Andrei Canta

Posted on • Originally published at deiucanta.com

Custom NextJS Server with Typescript

This article was originally posted on my personal blog.


There is an official NextJS guide on how to create a custom server. However, it only works with JavaScript. Please follow their guide and come back.

https://nextjs.org/docs/advanced-features/custom-server


  1. Rename server.js to server.ts.

  2. Update the scripts in package.json

   "scripts": {
   "dev": "ts-node server.ts",
   "build": "next build",
   "start": "NODE_ENV=production ts-node server.ts"
   }
Enter fullscreen mode Exit fullscreen mode
  1. Install ts-node
   yarn add ts-node
Enter fullscreen mode Exit fullscreen mode
  1. Add this section in tsconfig.json
   {
     // ...
     "ts-node": {
       "transpileOnly": true,
       "compilerOptions": {
         "module": "commonjs"
       }
     }
   }
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
inaara_kalani profile image
Inaara Kalani

It doesn't work for me. I'm getting this error:

\node_modules\ts-node\src\index.ts:859
return new TSError(diagnosticText, diagnosticCodes, diagnostics);
^
TSError: β¨― Unable to compile TypeScript:
error TS5095: Option 'bundler' can only be used when 'module' is set to 'preserve' or to 'es2015' or later.

Collapse
 
oyal profile image
oyal

Modify "bundler" to "node" in the ts.config.json file. You can view this tempalte.
github.com/vercel/next.js/blob/c30...

Collapse
 
vivek_iyer_48d0e5394cc399 profile image
Vivek Iyer

Same issue as @inaara_kalani
Got this error

`tsconfig.server.json:3:5 - error TS5095: Option 'bundler' can only be used when 'module' is set to 'preserve' or to 'es2015' or later.

3 "compilerOptions": {
~~~~~~~~~~~~~~~~~

Found 1 error in tsconfig.server.json:3`

Collapse
 
oyal profile image
oyal

Modify "bundler" to "node" in the ts.config.json file. You can view this tempalte.
github.com/vercel/next.js/blob/c30...

Collapse
 
arthurka profile image
ArthurKa

And? Wtf? Is that all?

Collapse
 
arthurka profile image
ArthurKa

Loool. Really worked. Thanks!

Collapse
 
masadamsahid profile image
Maulana Adam Sahid

Awesome πŸ”₯