Yern
Yern

Reputation: 333

How to limit access to Express API in DigitalOcean

I have 2 applications on DigitalOceans, an Express, API, and a React application. React application gets data from API. I want to make sure no one can access this API other than my React application. I'm using Ubuntu 18.04.

Upvotes: 2

Views: 328

Answers (2)

Willian
Willian

Reputation: 3405

You could use CORS in Express which is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain.

NOTE: I'm recommending this one given your app does not require login.

First, install the library in your backend:

npm install cors

Second, setup the allowed origin:

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}

app.use(cors(corsOptions))

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for only example.com.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

You could find more examples in CORS Middleware

Upvotes: 1

louis.sugar
louis.sugar

Reputation: 191

You'll want to look into request authorisation methods. If you only want a simple request authorisation system that does not take into account individual users, you can create an environment variable on the frontend with an auth token, and send this with every request, then only respond with data if the authToken matches the one saved on your backend.

If you have multiple users using your app I'd recommend looking into JWTs (https://jwt.io)

Upvotes: 0

Related Questions