DEV Community

Cover image for Enhance your backend security with these tips.
Beey
Beey

Posted on

Enhance your backend security with these tips.

Install CORS

Installing CORS or Cross-Origin Resource Sharing is great security for the backend-side of your website due to a strict policy browsers use by default:

webpages are blocked from requesting data from a different domain, port, or protocol to protect user security.

CORS uses special HTTP headers like Access-Control-Allow-Origin to let servers safely lift this restriction for trusted external websites.

How to install CORS

To install CORS run the following command:

NPM: npm i cors
yarn: yarn add cors
bun: bun add cors
PNPM: pnpm add cors

Consequences of rejecting CORS

Rejecting CORS will hurt your website's security, Here is why.

Without CORS you will have to use a bypass with jsonp(json with padding), which is vulnerable and allows black-hat hackers to breach your website.

An example of this with CommonJS(CJS) is:


const express = require('express');

const app = express();

app.get('/api/user', (req, res) => {
  res.jsonp({ id: 101, name: 'Alice' });
});

app.listen(300);

Enter fullscreen mode Exit fullscreen mode

Hash passwords with bcrypt

Without this hackers can get into other people's accounts because the password has not been hashed.

Hashing wigth bcrypt is far easy if you downloaded the NPM package.

To hash a password here is an example using cjs(CommonJS):


const bcrypt = require('bcrypt');

const password = "example";

async function HashPassword() {
  const hashed = await bcrypt.hash(password, 10);
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

That is all for today's backend tips!

Top comments (0)