# expressjs

How to exclude index.html from static files in Express Js?

While working on my current project, I faced one weird issue. The issue is whatever changes I made to the code it's not getting reflected on the page. Also, the page which I see on the browser is completely different than what I'm sending from the server. Below is the code I'm talking about,

const express = require("express");
const path = require("path");

const root_directory = process.cwd();
const assets_directory = path.join(root_directory, "assets");

const app = express();
app.use(express.static(assets_directory, { index: false }));

app.get("*", (req, res) => {
res.send("Hello World");

app.listen(8010, () => {
console.log(`Server Started`);

As you can see in the above code, whatever the request URL it is, I'm sending "Hello World" as the response. But when I tried to load the webpage, what I'm getting is the "Welcome to Homepage" message on the page.

Hmm. It's weird. After a little debugging, I finally found the code which causes this issue. The code is,

const root_directory = process.cwd();
const assets_directory = path.join(root_directory, "assets");
app.use(express.static(assets_directory)); // This Line

For including static files like JS and CSS, I'm using express.static method to load files from the assets directory. In that folder, index.html also there. I'm unaware of index.html because it's an express js boilerplate I downloaded from GitHub. So whenever Express JS receives a GET request for a root URL(/), it'll send index.html as a response by default. If index.html not exists, Express JS will pass the control to the next router, in my case its app.get('*',()=>{}) method.

We can solve this issue using either excluding the index.html or by renaming it.

Excluding index.html file from the static directory

In express js, there is an option to configure whether to include index.html or not. Below is the code to disable index.html,

const root_directory = process.cwd();
const assets_directory = path.join(root_directory, "assets");
app.use(express.static(assets_directory, { index: false })); // Added index

The express static method accepts options as a second parameter. In that, we can pass {index: false} to exclude the index.html file from the static assets folder.

After restarting the express server, my issue got solved. Now I can see what I'm sending as a response in the app.get('*') method.