Serving static files In express

Serving static files In express

While developing a web application on Node.js, You may need to add either scripts, styles or fonts to the frontend, But you can't do that the normal way. You have to let the server know you'll be using them.

Serving static files in express

You'll be using the app.use() function to do this, Assuming your static files are in a public directory. you can simply use it this way app.use(express.static('public')) now express will look this up in the public folder.

What if you want to create a virtual path prefix you'll use in the frontend to locate the file, you can simply create it this way app.use('/static', express.static('public'))

  • /static/js/app.js if app.js is what you need in js folder
  • /static/css/style.css if style.css is what you need in css folder

  •   font-family: BreeSerif;
      src: url('/static/fonts/BreeSerif-Regular.ttf');
    }
    

if BreeSerif-Regular.ttf is the font you need in fonts folder

Thanks for reading.