Fixing Express.js TypeError: Path Must Be Absolute or Specify Root in res.sendFile

Updated: December 28, 2023 By: Guest Contributor Post a comment

The error ‘Express.js TypeError: path must be absolute or specify root to res.sendFile’ occurs when attempting to send a file to the client using the res.sendFile method in Express.js without providing an absolute path to the file or without setting the root option.

Understanding the Error

Express.js’ res.sendFile function requires either an absolute path or the root directory to be specified so it can correctly locate and send the file over HTTP. An absolute path is the complete path to a file from the root of the filesystem. If the path provided is not absolute, Express.js cannot determine the file’s location.

Methods to Fix the Error

There are two primary ways to resolve this error:

  1. Provide an absolute path to the file.
  2. Use the root option to specify the root directory.

1. Providing an Absolute Path

To supply an absolute path in Node.js, you can use the path module, which provides utilities for working with file and directory paths. Specifically, the path.resolve() method can be used to turn a relative path into an absolute one.

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

const app = express();

app.get('/', function(req, res) {
    const filePath = path.resolve(__dirname, 'public', 'index.html');
    res.sendFile(filePath);
});

app.listen(3000, function() {
  console.log('Server is running on port 3000');
});

2. Using the root Option

Alternatively, you can specify the root directory where the file is located using the root option in the res.sendFile method.

const express = require('express');

const app = express();

app.get('/', function(req, res) {
    const filePath = 'index.html';
    // Set the 'root' option to the absolute path of the directory containing the file
    res.sendFile(filePath, { root: path.join(__dirname, 'public') });
});

app.listen(3000, function() {
  console.log('Server is running on port 3000');
});

In both examples above, replace 'public' with the actual directory name containing your file and 'index.html' with the actual file you are serving. With either method, you’re ensuring that Express.js has the absolute path it needs to send the file correctly.

Once you implement one of these solutions, the ‘Express.js TypeError: path must be absolute or specify root to res.sendFile’ error should no longer occur, and your file will be served correctly to the client.