Search code examples
node.jsexpress

Express.js file-system based router


I just would like to ask, is it possible to do file-system based routing with express.js routes? Something like Next.js has.


Solution

  • Well, I do not recommend this as it can turn out to be a security issue. However if you really want to, it is quite easy to do. You can just listen to app.get("*"). An example shown below:

    let path = require("path")
    let express = require("express")
    let app = express()
    let fs = require("fs")
    
    app.get("*", (req,res) => {
        let filePath = path.join(__dirname, "routes", req.path)
        if(!fs.existsSync(filePath)) return res.sendStatus(404)
        res.sendFile(filePath)
    })
    
    app.listen(80)
    
    

    This recurses and loads any file that may be there in the "routes" folder (or any subdirectories). I did this with html so i did sendFile(), however I believe it should work with .render() too.

    I highly recommend against this as it can potentially allow people to climb up your directory structure with some messing around with the path they try to fetch.