Hairi
Hairi

Reputation: 3733

Best approach to serve user protected files - Node.js, Express server

I would like to know what is the best way to serve private(to an user) files from my Express server (API).

Every user may have associated files that contain private data and should not be available publicly, not to other users.

This means I cannot simply use app.use('/static', express.static(path.join(__dirname, 'public')))

Many experts point out that the best way to serve static files/content not from the server at all, but from cloud services like Amazon S3. I welcome that idea since that would unburden the server from delivering static (potentially big) files. But files on such cloud storage cannot be private or associated to a specific user, can they?

I came across to other example that point out how to protect express.static directory. But it seems to me that this example only checks if the user is authenticated - not authorized as I need. Every user granted access to the static directory would be granted access other user's files as well. This is not what I want.

The last options - that is fairly easy to implement - is to have the files stored into the database. I imagine having something like this :

var fileSchema = new mongoose.Schema({
    user: { type: Schema.Types.ObjectId, ref: 'User' },
    name: String,
    desc: String,
    file:
    {
        data: Buffer,
        contentType: String
    }
});

Thus the file is explicitly belonging to specific user and other users cannot access it even though authenticated in the system (I mean the logic here is pretty straight forward).

But it seems that storing files in the database is not a good practice. It impose extra load on the DB and the API. This is why Im searching for other possible solutions.

Any advice/comment/solution would be very much appreciated! Thanks.

Upvotes: 3

Views: 249

Answers (0)

Related Questions