DEV Community

Cover image for Make Your Own Server Using Express.js and Node.js
Pranav Yamjal
Pranav Yamjal

Posted on

Make Your Own Server Using Express.js and Node.js

What Will You Learn?

In this blog, you’ll learn how to create a basic server using Node.js and Express.js. We’ll cover the fundamentals of servers and clients, set up a Node.js environment, install dependencies, and guide you through the code to build a simple server. By the end, you’ll have a functional server that can handle requests and respond to clients.

Here’s what we’ll go over:

  1. Understanding what a server is
  2. Setting up Node.js and Express.js
  3. Managing sensitive information with dotenv and gitignore
  4. Writing the code for a functional server
  5. Breaking down each part of the server code

1. Prerequisites

  • A basic understanding of programming; if you're familiar with JavaScript, that's a plus.
  • Basic understanding of client-server architecture.
  • That’s all!

2. What is a Server?

Image description

  • A server is software that listens for and responds to requests. In other words, a server is ready to fulfill requests from clients.

  • The client is the requester, and the server is the responder.

  • Think of it as a classic cook and waiter analogy, where the cook represents the server and the waiter represents the client. The exchange of orders (requests) and food (responses) symbolizes the communication protocols, such as HTTP and TCP/IP, though we won’t dive deep into these here.


3. How Do Node.js and Express.js Help Us Set Up Our Own Server?

Image description

i) Node.js

  • Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. According to the official Node.js site, it provides a way to execute JavaScript outside of a browser, making it perfect for building back-end applications.

  • JavaScript is platform-independent, meaning code written in JavaScript can run on various environments that support it. For instance, JavaScript code typically runs in browsers (like Chrome’s V8 engine). However, if you want to execute JavaScript outside of the browser, such as in VS Code, you’ll need a runtime environment—and that’s where Node.js comes in. Node.js provides all the necessary execution capabilities to run and debug JavaScript code directly on your machine or within an IDE like VS Code.

ii) Express.js

  • Express is a fast, unopinionated, minimalist web framework for Node.js. It offers a rich set of features for building web and mobile applications.

  • In simpler terms, Express.js acts as a communication bridge between the client and server. You could think of Express.js as the "road" that allows requests and responses to travel between the client and server.

  • With Express, we can easily handle requests from clients and send responses from the server, making it a powerful and efficient tool for building a web server.


4. Understanding dotenv and gitignore

Image description

i) dotenv

  • Install dotenv using:
npm install dotenv
Enter fullscreen mode Exit fullscreen mode

This command installs dotenv into your project and generates a package-lock.json file.

  • Create a file named .env
    • .env is a file for storing environmental variables that are sensitive and could pose security risks if exposed
    • Examples include database passwords, project URLs, API keys, etc.
    • For this project, we'll use PORT=3000 as an example
    • When app.listen() is called, it fetches data from the .env file using process.env.PORT, ensuring data integrity and security

ii) .gitignore

  • Create a .gitignore file using:
code .gitignore
Enter fullscreen mode Exit fullscreen mode
  • Files listed in .gitignore won't be staged or committed to Git
  • Add these to your .gitignore:
    • node_modules: Prevents repository redundancy and keeps it lightweight. Contributors can install dependencies locally using npm install
    • .env: Protects sensitive information

5. Setting Up the Server

i) npm initialization

npm init
Enter fullscreen mode Exit fullscreen mode
  • Running this command in VS Code's terminal prompts for project information:
    • Project name
    • Author
    • Version
    • Other details
  • npm (Node Package Manager) is used to set up Node.js projects
  • Creates a package.json file containing:
    • Project dependencies
    • Versions
    • Entry point
    • Basic project information

ii) Setting up scripts

Add this to your package.json:

{
  "scripts": {
    "start": "node index.js"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Scripts are functions that execute when called
  • Example: Running npm run start will execute node index.js
  • This improves coding efficiency by providing shortcuts for common commands

iii) Setup active server

index.js

require('dotenv').config()

const express = require('express')

const app = express()

const githubData = 
    {
        "login": "pranavyamjal",
        "id": 69851016,
        "node_id": "MDQ6VXNlcjY5ODUxMDE2",
        "type": "User",
        "user_view_type": "public",
        "site_admin": false,
        "name": "Pranav Yamjal",
        "company": null,
        "blog": "",
        "location": "Pune,Maharashtra,India",
        "email": null,
        "hireable": true,
        "bio": "Exlploring the coding universe",
        "twitter_username": "pranavyamjal",
        "public_repos": 8,
        "public_gists": 0,
        "followers": 2,
        "following": 4,
        "created_at": "2020-08-18T11:45:25Z",
        "updated_at": "2024-11-01T03:28:37Z"
      }


app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.get('/twitter', (req, res) => {
    res.send('pranavyamjal')
})

app.get('/login',(req,res) => {
    res.send('<h1>Please Login!!!!!!!!</h1>')
})

app.get('/github', (req, res) => {
    res.send(githubData)
})

app.listen(process.env.PORT, () => {
  console.log(`Example app listening on port ${process.env.PORT}`)
})

Enter fullscreen mode Exit fullscreen mode

6. let's understand code

require('dotenv').config()
Enter fullscreen mode Exit fullscreen mode
  • This line loads environment variables from a .env file into process.env. This allows you to store sensitive information, such as your app's PORT or API keys, in a separate file instead of hardcoding them into your code.
const express = require('express') 
Enter fullscreen mode Exit fullscreen mode
  • Here, you import the Express library, which provides a web framework for handling HTTP requests and creating APIs.
const app = express()
Enter fullscreen mode Exit fullscreen mode
  • This creates an instance of an Express application, which allows you to define routes and middleware for handling HTTP requests.
const githubData = { /* JSON object data */ }
Enter fullscreen mode Exit fullscreen mode
  • This defines an object named githubData with some information about a GitHub user. The data includes details such as login name, ID, location, bio, and other GitHub profile information, which can be used for serving responses.
app.get('/', (req, res) => {
  res.send('Hello World!')
})
Enter fullscreen mode Exit fullscreen mode
  • This defines a route for the root path (/). When a GET request is made to this path, the server responds with the text "Hello World!".
app.get('/twitter', (req, res) => {
    res.send('pranavyamjal')
})
Enter fullscreen mode Exit fullscreen mode
  • This defines a route at /twitter. When a GET request is made to this endpoint, it responds with the Twitter username, "pranavyamjal".
app.get('/login',(req,res) => {
    res.send('<h1>Please Login!!!!!!!!</h1>')
})
Enter fullscreen mode Exit fullscreen mode
  • This route, located at /login, responds to a GET request with an HTML message (<h1>Please Login!!!!!!!!</h1>), displaying a "Please Login" message on the page.
app.get('/github', (req, res) => {
    res.send(githubData)
})
Enter fullscreen mode Exit fullscreen mode
  • This defines a route at /github. When a GET request is made to this endpoint, it responds with the githubData JSON object defined earlier, which provides GitHub profile information.
app.listen(process.env.PORT, () => {
  console.log(`Example app listening on port ${process.env.PORT}`)
})
Enter fullscreen mode Exit fullscreen mode
  • This starts the server, making it listen for requests on the port specified by process.env.PORT. When the server starts, it logs a message indicating the port it's running on, such as "Example app listening on port 3000".

7. Conclusion

Congratulations! You've just created your first Node.js server using Express. Let's recap what we've learned:

  • Understanding the basics of client-server architecture
  • Setting up a Node.js development environment
  • Managing sensitive information with dotenv
  • Creating basic server routes with Express.js
  • Handling different types of HTTP requests

This is just the beginning of your journey into backend development. With these fundamentals, you can now explore more advanced concepts like:

  • Database integration
  • Authentication and authorization
  • RESTful API design
  • Middleware implementation
  • Error handling

8. Suggestions for Practice

  1. Try creating new routes with different HTTP methods (POST, PUT, DELETE)
  2. Experiment with sending different types of responses (JSON, HTML, files)
  3. Add error handling to your routes
  4. Create a simple API that interacts with a mock database
  5. Implement basic middleware for logging requests

Thank You!

Thank you for reading my first blog! If you found this helpful, please feel free to:

  • Share this with others who are learning Node.js
  • Follow me on Twitter @pranavyamjal
  • Check out my other projects on GitHub
  • Leave comments or suggestions for improvement

Your feedback helps me create better content and helps our community grow stronger. Happy coding! 🚀


Top comments (4)

Collapse
 
programmerraja profile image
Boopathi

This is a great introduction to building servers with Node.js and Express! The step-by-step guide makes it easy to follow along. I'm definitely going to try building a simple API with a mock database as suggested.

Collapse
 
pranavyamjal profile image
Pranav Yamjal

Thank you! I’m glad the guide was helpful. Best of luck with your API—let me know how it goes!

Collapse
 
jitendra_rawal_4544 profile image
Jitendra Rawal

Very Helpful

Collapse
 
pranavyamjal profile image
Pranav Yamjal

Thank you! I'm glad you found it helpful.