Combine Typescript with NextJS and Express

Narongsak Keawmanee
Medvine Tech
Published in
3 min readDec 16, 2018

Today we will setup project from scratch and combine TypeScript, NextJS and Express together. at Medvine we had NextJs combine with Express to be standard stack for internal service. and today I will add Typescript into that stack. so let get started.

Install standard NextJS with Typescript

NextJs provide script that will lead us to getting started with NextJs and Typescript easier by this command.

npx create-next-app --example with-typescript <project_name>

Let run yarn dev and see what we got at http://localhost:3000/

first page created by create-next-app

And if we look and pages directory. we will see file index.tsx and about.tsx which is extension of typescript file.

Then we need to install express

yarn add express 
yarn add @types/express nodemon --dev // for typescript checker

We need to create file name server.tsx for run express and use this code.

Change script on package.json file to.

"scripts": {    "dev": "nodemon -w controllers -w server.tsx --exec yarn type-check",    "build": "next build",    "start": "next start",    "type-check": "tsc && node dist/server.js"}

On dev command we use Nodemon to watch file change at folder controllers and file server.tsx. if have any change will run type-check command and run dist/server.js

And we need to change config at tsconfig.json like this.

outDir — directory of output files after compiled script.
jsx — need to be react for es6 command.
module — use commonjs so we can use es6 import.
include — source directory of file before complier.

Then run yarn build for build NextJS first and after that we run yarn dev for watch file and complier.

Goto http://localhost:3000/ we will see same pages. but this time we see log that said server ready on port 3000. that mean we combine express to this project successfully.

result of yarn dev

Next step. we need to create controller endpoint. create new folder call controllers and create file name hi.tsx then add this code.

Go back at server.tsx file. import hi.tsx and use this controller at app block scope. the complete file should look like this.

Then run http://localhost:3000/hi we will see result of new endpoint

result at http://localhost:3000/hi

I appreciated all cup of coffee. you can donate coffee at button below.

https://www.buymeacoffee.com/klogic

Now we can use Typescript with NextJS and Express. you can look all source code here.

--

--

Narongsak Keawmanee
Medvine Tech

Software Engineer at Refinitiv • Highly ambitious • Love working with great people • Never Stop Learning