== How to fix it in Express.js

=== Code examples

:code_impact: read

include::../../common/fix/code-rationale.adoc[]

==== Noncompliant code example

[source,javascript,diff-id=1,diff-type=noncompliant]
----
const path = require('path');

function (req, res) {
  const targetDirectory = "/data/app/resources/";
  const userFilename = path.join(targetDirectory, req.query.filename);

  res.sendFile(userFilename); // Noncompliant
}
----

==== Compliant solution

[source,javascript,diff-id=1,diff-type=compliant]
----
const path = require('path');

function (req, res) {
  const targetDirectory = "/data/app/resources/";
  const userFilename = req.query.filename;

  res.sendFile(userFilename, { root: targetDirectory });
}
----

=== How does this work?

:auto_canonicalization_function: res.sendFile() (used with options.root)

include::../../common/fix/function-based-validation.adoc[]

include::../../common/fix/self-validation.adoc[]

=== Pitfalls

:joining_docs: https://nodejs.org/api/path.html#pathresolvepaths
:joining_func: path.resolve

include::../../common/pitfalls/path-joining.adoc[]


