Writing Secure Code With JavaScript

Writing Secure Code With JavaScript

When writing code with JavaScript, one of the most important things a developer can do is make sure their code is secure. To achieve this, there are a number of best practices, code examples and tools that developers should include in their projects.

Best Practices

1. Always validate user input - before allowing a user to use your website or application, be sure to validate the inputs they provide. This can include things like validating email addresses, ensuring passwords meet certain criteria, and ensuring fields are not left blank, among other things.

2. Sanitize all user input - after validating, you should also sanitize any user input entered into your application. This involves removing malicious scripts or potentially dangerous code from being executed on your webpages.

3. Use HTTPS for all data transmission - it is not enough to just secure the data at rest; also ensure that the data is encrypted as it is being transmitted as well. A great way for developers to do this is to enable HTTPS throughout the application, which can often be done with a few lines of code.

4. Implement two-factor authentication - adding extra layers of security to your application is always a great idea. Two-factor authentication (2FA) adds an extra layer of security on top of a user’s password, making it much harder for attackers to gain access.

Code Examples

Below are some basic code examples that developers can use to better secure their applications.

//Example of code to validate user login information
function validateLogin(userEmail, userPassword) {
  // Check if empty
  if(userEmail == "" || userPassword == "") {
    alert("No fields can be left empty!");
    return false;

  // Verify email address
  var re = /\S+@\S+\.\S+/;
  if (!re.test(userEmail)) {
    alert("Please enter a valid email address!");
    return false;

  // Verify password
  if (userPassword.length < 8) {
    alert("Your password must contain at least 8 characters!");
    return false;

  return true;
//Example of basic code to clean unsefe user inputs
function sanitizeInput(userInput) {
  //Replace all HTML tag characters with spaces
  var cleanInput = userInput.replace(/<[^>]*>/g, ' ');
  //Strip out non-alphanumeric characters
  cleanInput = cleanInput.replace(/[^a-z^0-9]/gi, '');
  return cleanInput;
//Example of code to enable HTTPS
function enableHTTPS() {
  // Set up HTTPS
  const https = require('https');
  const fs = require('fs');

     key: fs.readFileSync('server.key'),
     cert: fs.readFileSync('server.cert')
  }, app).listen(8080, () => {
    console.log('HTTPS Server Running on port 8080.');
Two-Factor Authentication (2FA):
//Example of code to implement 2FA
var express = require('express');
var app = express();
var twoFactor = require('node-2fa');

app.get('/two-factor', function(req, res) {

  // Generate a secret key
  var secretKey = twoFactor.generateSecret({name: 'My App'});

  // Generate a QR code
  var qrCodeUrl = twoFactor.getQRCodeGoogleUrl('My App', secretKey);

  // Create an actual QR code image
  var qrCodeImage = twoFactor.getQRCodeImage(secretKey, 10);

  // Generate a 6-digit one-time-password
  var oneTimePassword = twoFactor.generateOTP(secretKey);

  // Validate a 7-digit one-time-password
  twoFactor.verifyOTP(secretKey, oneTimePassword);



Writing secure code with JavaScript is essential for any developer looking to create an application that is free from malicious attacks. By adhering to these best practices you can ensure that you'll be protected from various attacks by threat actors.

Did you find this article valuable?

Support Anthony Smith by becoming a sponsor. Any amount is appreciated!