Home > Net >  How do I password protect a folder with Node.js and Express?
How do I password protect a folder with Node.js and Express?

Time:04-21

I'm making a simple web server with Node.js and Express. I'm hosting many static files, including a Unity WebGL game.

For the game to work properly, many assets need to be loaded. Is there some kind of easy way I could store a cookie with a password (on a login page), and if the password cookie is present and has the right value, all requests are accepted?

Still very new to web server stuff, all I've done so far is Discord bots.

So basically all I'm trying to do is have a simple password page (and maybe have some kind of a delay when it checks if the password is correct) and then let you load things in one folder.

Hope that's easy to do. Sorry if my question is dumb.

CodePudding user response:

Setting a cookie

to set a cookie you can use something like expresses cookie-parser middle-ware check it here

Giving access

you can send some kind of uuid or access token from the client side using something like fetch api or an ordinary XMLHttpRequest refer here and use some logic to give access to the file

code

var express = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/getfile', (req, res) => {
    const code = req.cookies.mysecertcode;
    if(code = secert) {
         res.send("correct token")
    } else {
         res.send("incorrect token")
    }

})

app.listen(8080)

this code is just a simple code I made you can use your own

Hope this can help you thank you

  • Related