DEV Community

Luckey
Luckey

Posted on

Create a simple Node Server Skeleton.

Introduction

This tutorial is quite useful for quick start for many simple projects which doesn't need complex functionalities or projects which are for tutorial purpose.

If you want to build a more complex Node Server with express, routers, controllers, databases, Redis and etc. You can ahead to my another article.


Code

Set up environment

First, you would need to install the necessary dependencies. In your terminal, navigate to the root directory of your project and run the following command to initialize packages:

npm init
Enter fullscreen mode Exit fullscreen mode

Install express and necessary packages with npm

npm install express cors dotenv
Enter fullscreen mode Exit fullscreen mode

or install packages with yarn

yarn add express cors dotenv
Enter fullscreen mode Exit fullscreen mode

If you are using TypeScript, you must also install the following packages

npm install @types/express @types/cors
Enter fullscreen mode Exit fullscreen mode

or install packages with yarn

yarn add @types/express @types/cors
Enter fullscreen mode Exit fullscreen mode

Server.js (JavaScript)

Once express is installed, you can create the server file. In your project directory, create a file called server.js and add the following code:

import express from "express";
import cors from 'cors';
import dotenv from "dotenv";

// Get environment variables
dotenv.config()

// Create the express server and configure it to use json
const app = express();
app.use(express.json());

// Configure cors policy
app.use(cors())

// Set up a API call with GET method
app.get('/data', (req, res) => {
  // Return some sample data as the response
  res.json({
    message: 'Hello, world!'
  });
});

// Start the server on port configured in .env (recommend port 8000)
app.listen(process.env.PORT, () => {
  console.log(`SERVER IS RUNNING AT PORT ${process.env.PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Server.ts (TypeScript)

the only different between Server.js and Server.ts is showed below:

// You need to classify the type of variable
const app: Application = express()
Enter fullscreen mode Exit fullscreen mode

Common Errors

SyntaxError: Cannot use import statement outside a module
Solution: Add below line to your Package.json

"type": "module",
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, creating a simple Node server skeleton is a straightforward process that involves setting up a new Node project, installing the necessary dependencies, and configuring the basic server structure.

Top comments (0)