Creating a web application serving HTML and CSS with Node.js and Express

Creating a web application with Node.js and Express that serves HTML and CSS files is a great way to understand the basics of server-side web development. Here’s a step-by-step guide to get you started:

Step 1: Setting Up Your Environment

  1. Install Node.js and npm: Ensure Node.js and npm (Node Package Manager) are installed. You can download them from the official Node.js website.
  2. Verify Installation: Open a terminal and type node -v and npm -v to check the versions and confirm their successful installation.

Step 2: Create Your Project

  1. Create a New Directory: Make a new folder for your Express app, for example, myexpressapp.
  2. Initialize Your Project[Not Required]: Navigate to your project directory in the terminal and run npm init. Answer the setup questions to create a package.json file.

Step 3: Install Express

  1. Install Express: In your project directory, run npm install express --save to install Express and add it to your project dependencies.

Step 4: Set Up Your Express App

  1. Create an Entry File: Create a file named app.js in your project folder. This will be your main server file.
  2. Write Server Code:
   const express = require('express');
   const app = express();
   const port = 3000;

   app.listen(port, () => {
     console.log(`Server running on http://localhost:${port}`);
   });

Step 5: Serve HTML and CSS Files

  1. Create a Public Directory: Inside your project folder, create a new folder named public. This is where you’ll store your HTML and CSS files.
  2. Add HTML and CSS Files: Place your HTML file(s) and CSS file(s) in the public folder. For example, create index.html and style.css.
  3. Serve Static Files: Modify app.js to serve static files from the public directory:
//Complete code
const express = require('express');
const path = require('path');
const app = express();
const PORT = 3000;


// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 6: Running Your Express App

  1. Start the Server: Run node app.js in your terminal to start your Express server.
  2. Access Your Web Page: Open a browser and go to http://localhost:3000. You should see your HTML page rendered with the applied CSS styles.

Step 7: Additional Features

  1. Custom Routes: You can create specific routes for different pages. For example:
   app.get('/about', (req, res) => {
     res.sendFile(__dirname + '/public/about.html');
   });
  1. Error Handling: Add a 404 error handler to manage unknown routes:
   app.use((req, res) => {
     res.status(404).send('404: Page Not Found');
   });

Step 8: Test and Debug

  1. Test Your App: Navigate through your app in a web browser to ensure all pages load correctly and the CSS is applied.
  2. Debug: If something doesn’t work, check your server console for errors and ensure your file paths are correct.

Final Thoughts

  • Code Organization: Keep your project organized by separating HTML, CSS, and JavaScript files into appropriate directories.
  • Learning More: Explore more about Express.js and its features by reading the official documentation.
  • Security and Performance: As you get more comfortable, consider looking into security best practices and performance optimization for Express apps.

By following these steps, you should be able to create a basic Express application that serves HTML and CSS files, which is a fundamental skill in web development. As you grow more confident, you can start adding more complex features like dynamic content, template engines, and database integration.

Hello, I’m Anuj. I make and teach software.

My website is free of advertisements, affiliate links, tracking or analytics, sponsored posts, and paywalls.
Follow me on LinkedIn, X (twitter) to get timely updates when I post new articles.
My students are the reason this website exists. ❤️

Feedback Display