DEV Community

loading...
Cover image for Setting up Node js, Express, Mongodb and Mongoose with TypeScript

Setting up Node js, Express, Mongodb and Mongoose with TypeScript

kalashin1 profile image Kinanee Samson ・4 min read

This week i had to setup a node js server for a project that i will be working on for the next 2 months, i had built node js servers with plain JavaScript but JavaScript's dynamically typed system is always a pain to deal with and i opted to use TypeScript for sanity and clarity, i also wanted all the cool features that comes along with using TypeScript like auto-completion and full editor support. I don't know if you have used express in the past before, but i strongly advice that you are comfortable using express and the other tools i will make reference to in this article, i will not go into much detail about using them because it is outside the scope of this article, I just want to show you how to set up your local development environment using TypeScript. Let's dive in.

Install Node js

For you to actually use node js on your computer you have to install it, you can head to their website to download the latest version of node js to your computer..

Create a project directory

If you successfully installed node js on your computer, you can open up a terminal or a command prompt and hit node -v this throws back the version of node js you have installed on your computer if there's one. From the command line enter the following command to create a new project. mkdir server && cd server this command creates a folder and navigates to the newly created folder, in our instance the folder is server but you can name it whatever you feel like.

Start an new Node js App

From the terminal enter npm init -y to generate a package.json file that will keep track of the dependencies we are going to install as we go along the project.

Install TypeScript

To install TypeScript hit npm i typescript and this installs TypeScript from npm for us, next thing is to install express and setup a basic express server, but wait we are using TypeScript right?

Install Express

From the command line run npm i express and when that is done, we need to install the type definition for express so we don't get an error in our editor while using express. Next thing is to run npm i -D @types/express we install the express types and we save it to our dev dependencies.

Setting up An Express Server

From the command line/terminal run code . make sure you are inside the server directory. This opens VS code with the current folder as our work space, create a file and name it whatever you want but it should have a .ts extension. In my case I'm going to name this file app.ts. Our basic express server should have the following contents

import * as express from 'express'

const app = express()

const PORT = 8080

app.get('/', (req: express.Request, res: express.Response) => {
    res.setHeader('Content-Type', 'text/html')
    res.end('<h1>Hello World</h1>')
})

app.listen(PORT, () => console.log(`app running on port ${PORT}`))
Enter fullscreen mode Exit fullscreen mode

Running the Server

To run this server we need to install nodemon to our dev dependencies, this is a package that will watch our server for changes and then it will automatically restart the server so that the changes takes effect without us having to do so manually. To install nodemon run npm i -D nodemon. Next thing is to open up the package.json file and add the following scripts to the script object;

"scripts": {
    "compile": "tsc app.ts -w",
    "start": "nodemon app"
}
Enter fullscreen mode Exit fullscreen mode

Once you are done adding those scripts, from the command line run the compile script npm run compile this script compiles our TypeScript to JavaScript, then you can open up another terminal session and run the start script npm run start and this will now serve our file, you should see app running on port 8080 in the current terminal if everything works according to plan.

installing Mongodb and Mongoose

Since we are going to be working with Mongodb and Mongoose we need to install it, and to do that open up another terminal session and run the following commands npm i mongodb mongoose when Mongodb and Mongoose are done installing, you need to install the type definitions for Mongodb and Mongoose like we did with express, ensure you install the type definitions to the dev dependencies since we would not be needing them for production, we only use them to ensure that we don't get errors in VS code while working with the packages. To install the type definitions run npm i -D @types/mongodb @types/mongoose from the command line.

Connecting to Mongodb with Mongoose

Now we have Mongodb and Mongoose installed on our computer, we can connect to it. I have to say that i have mongodb installed locally on my computer and i cannot start going into detail about setting up Mongodb locally or in the cloud because it is outside our scope. Open your server file, the one written with typescript, not the compiled JavaScript file and add the following.

//app.ts


import * as express from 'express'
import * as mongoose from 'mongoose'

const app = express()

const PORT = 8080

// THIS STRING IS THE LINK TO OUR MONGODB
const url = 'mongodb://localhost:27017/test'

// mongodb connection
mongoose.connect(url, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true})
.then(result => app.listen(PORT, () => console.log(`app running on port ${PORT}`)))
.catch(err => console.log(err))


app.get('/', (req: express.Request, res: express.Response) => {
    res.setHeader('Content-Type', 'text/html')
    res.end('<h1>Hello World</h1>')
})

app.listen(PORT, () => console.log(`app running on port ${PORT}`))
Enter fullscreen mode Exit fullscreen mode

Save the file, the TypeScript compiler will auto compile our TypeScript to JavaScript because we ran it with the watch flag and nodemon will automatically restart the server so we can see our changes take effect. If everything happened successfully then you should see app running on port 8080 in the terminal and if you open up your browser and navigate to localhost:8080/ you should see a big Hello World sent back to us. You can go on and continue building your server from where we stopped.

That's it for this article, i hope you learned something today, feel free to like and leave a comment below

Discussion (4)

pic
Editor guide
Collapse
tbell511 profile image
Tyler Bell

Amazing! This was a great read.

Collapse
kalashin1 profile image
Kinanee Samson Author

Glad you found it useful

Collapse
nathbabs profile image
Nathaniel

Where does it output the compiled files ?

Collapse
kalashin1 profile image
Kinanee Samson Author

Like i said it is outside the scope of this article but normally you will find it in the same directory as the TypeScript file.. Look closely