Node Fastify – serve images located in upload folder

Make files/images available to be access, when we navigate to

localhost:8000/properties/files/[image name]

localhost:8000/properties/files/1635843023660-profile.jpg

File Structure

node_modules
src/
uploads/
    1635843023660-profile.jpg
    1635843023668-home.jpg
...
.env
package.json

index.js

import Fastify from "fastify";
import FastifyStatic from "fastify-static";
import path from "path";
import { propertiesRoutes } from "./routes/properties.js";
...
export const fastify = await Fastify({ logger: process.env.LOGGER || true });

const __dirname = path.resolve(path.dirname(""));
fastify.register(FastifyStatic, {
  root: path.join(__dirname, "uploads"),
});
fastify.register(propertiesRoutes, { prefix: "/properties" });
...

routes/properties.js

export const propertiesRoutes = function (fastify, opts, done) {
  ...
  fastify.get("/images/:name", (req, res) => {
    res.sendFile(process.cwd() + "/uploads/" + req.params.name);
  });
  done();
};

as of right now I’m getting

{“message”:”Route GET:/properties/images/1635843023660-profile.jpg not found”,”error”:”Not Found”,”statusCode”:404}

Answer

When not specifiying a prefix in your FastifyStatic config, the default / will be used. So in order to access your static files you need to change your request path from /properties/images/<your-img.jpg> to /images/<your-img.jpg>.

Alternatively you could use a custom prefix like public like they did in the documentation:

fastify.register(require('fastify-static'), {
  root: path.join(__dirname, 'uploads'),
  prefix: '/public/',
})

and then request it with /public/images/<your-img.jpg>.