Serving Static Files and Templates
# CHAPTER 8
Serving Static Files and Templates
1. Introduction
While Express is world-famous for building JSON-based REST APIs, it is also fully capable of operating as a traditional web server that delivers full HTML pages to the browser. In this chapter, we will learn how to configure Express to serve static assets (like CSS, images, and vanilla HTML files) and explore Template Engines, which allow us to inject dynamic server-side data directly into HTML before sending it to the user.2. Learning Objectives
By the end of this chapter, you will be able to:-
Use the built-in
express.static()middleware.
- Expose a public directory for images and CSS.
- Understand the concept of Server-Side Rendering (SSR).
- Configure and use the EJS (Embedded JavaScript) template engine.
3. Beginner-Friendly Explanation
Imagine a library (Your Server).- Static Files: A user walks in and asks for a specific history book (an Image or CSS file). The librarian knows exactly where it is, pulls it off the shelf, and hands it directly to the user. The book never changes.
- Templates: A user walks in and asks for a personalized report containing their name and current account balance. The librarian cannot pull a pre-written book off the shelf. Instead, they grab a blank template, fill in the user's specific data using a typewriter, and *then* hand the customized page to the user. This is Server-Side Rendering.
4. Serving Static Files (express.static)
By default, Node.js protects every file on your server's hard drive. If you place a logo named logo.png in your project folder, and a user visits http://localhost:3000/logo.png, Express will block them with a 404 error. We must explicitly tell Express to make a specific folder public.
Step 1: Create a folder named public in your project root. Inside it, create a css folder and an images folder.
Step 2: In index.js:
*Now, if you put logo.png inside the public/images/ folder, anyone on the internet can view it by visiting http://localhost:3000/images/logo.png!*
5. Why Use Template Engines?
If you want to send an HTML page to a user, you can useres.sendFile(). But what if you want the HTML page to say "Welcome, Alice!"? A static HTML file cannot read database variables.
A Template Engine allows you to write HTML infused with JavaScript variables. Express processes the template, injects the data, generates a pure HTML string, and sends it to the browser.
6. Setting Up EJS (Embedded JavaScript)
EJS is the most popular, beginner-friendly template engine for Express.Install:
Configure Express (index.js):
7. Rendering a Dynamic Template
Step 1: Create a folder namedviews. Inside it, create profile.ejs.
Notice the special <%= %> syntax. This tells EJS to inject a variable here.
views/profile.ejs:
Step 2: Render it in your Route (index.js).
Instead of res.send() or res.json(), we use res.render().
*When the user visits /profile, Express stitches the data into the HTML and sends a complete webpage!*
8. Backend Workflow: SPAs vs SSR
In modern development, using EJS (Server-Side Rendering) is becoming less common. Today, developers usually build Single Page Applications (SPAs) using React, Vue, or Angular. In the SPA model, Express does not render HTML at all; it strictly acts as a JSON API, and the React frontend builds the HTML in the user's browser. However, understanding EJS is still a mandatory foundational skill.9. Best Practices
-
Security with
path.join: Always usepath.join(__dirname, 'public')instead of just writing'public'. Depending on how you run your Node server via the terminal, relative paths can break.__dirnameguarantees an absolute path from the root of your hard drive, preventing crashes.
10. Common Mistakes
-
Leaking Server Files: Never put sensitive files (like
.envconfiguration files or raw backend code) inside yourpublicdirectory. Anything inside the directory passed toexpress.static()can be downloaded by anyone on the internet.
11. Exercises
-
1.
Explain the difference between serving a static file (like
style.css) and rendering a dynamic template (likedashboard.ejs).
12. Coding Challenges
-
Challenge: Using EJS, create a template called
inventory.ejs. Pass an array of items (e.g.,['Laptop', 'Mouse', 'Keyboard']) from your Express route to the template. Inside the.ejsfile, use a JavaScriptforEachloop to dynamically generate an HTML<ul>list of the items.
13. MCQs with Answers
Which built-in Express middleware is required to allow web browsers to access your CSS and image files?
When using a template engine like EJS, which Response method is used to process the template, inject data, and send the final HTML to the browser?
14. Interview Questions
- Q: Explain the concept of Server-Side Rendering (SSR). How does it differ conceptually from a Client-Side Rendering (CSR) architecture using a framework like React?
-
Q: Why must you explicitly declare a directory as "public" using
express.static()in Node.js? What are the security implications if Node allowed default access to all files?
15. FAQs
Q: Are there other template engines besides EJS? A: Yes! Pug (formerly Jade) and Handlebars (hbs) are very popular. However, EJS is preferred by beginners because its syntax is almost identical to standard HTML, whereas Pug uses a strict indentation-based syntax.
16. Summary
In Chapter 8, we transformed our Express server into a full-stack web application. By configuringexpress.static(), we securely opened a bridge for the public internet to access our CSS stylesheets and client-side images. Furthermore, by integrating the EJS template engine, we learned how to perform Server-Side Rendering, dynamically injecting backend variables into HTML templates before delivering a customized experience to the user.