Client-Side Security
Input Validation
Goal: To prevent malicious or invalid data from being submitted to the server.
Methods:
Regular Expressions: Use regular expressions to validate the format and content of user input.
Example:
function validateEmail(email) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); }
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
HTML5 Input Validation: Utilize built-in HTML5 input validation attributes to enforce data types and patterns.
Example:
<input type="email" name="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" />
Source: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Introduction
JavaScript Libraries: Leverage dedicated libraries such as
validator.js
for comprehensive input validation.Example:
const validator = require('validator'); function validateUsername(username) { return validator.isAlphanumeric(username) && validator.isLength(username, { min: 3, max: 15 }); }
Error Handling
Goal: Gracefully handle errors that occur on the client-side to prevent unexpected behavior and enhance user experience.
Methods:
Try-Catch Blocks: Use try-catch blocks to capture and handle exceptions.
Example:
try { // Code that might throw an error const data = JSON.parse(userResponse); } catch (error) { console.error('Error parsing response:', error); // Display a user-friendly error message }
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try…catch
Custom Error Classes: Define custom error classes to provide more specific error information.
Example:
class InvalidInputError extends Error { constructor(message) { super(message); this.name = 'InvalidInputError'; } } try { // Code that might throw an error } catch (error) { if (error instanceof InvalidInputError) { // Handle invalid input specifically } else { // Handle other types of errors } }
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
Secure Data Storage
Goal: Protect sensitive data from unauthorized access, modification, or disclosure.
Methods:
Local Storage: Use Local Storage to store small amounts of data securely on the user’s device.
Example:
localStorage.setItem('userToken', 'secret_token');
Source: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API
Session Storage: Store data that is specific to the current browsing session.
Example:
sessionStorage.setItem('cart', JSON.stringify(cartItems));
Source: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API
IndexedDB: Use IndexedDB for storing larger amounts of structured data, such as user profiles or offline content.
Example:
const request = indexedDB.open('myDatabase', 1); request.onsuccess = (event) => { const db = event.target.result; // Perform operations on the database };
Source: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
Cross-Site Scripting (XSS) Protection
Goal: To prevent malicious scripts from being injected into the application and executed in the user’s browser.
Methods:
Output Encoding: Encode all user-generated content before displaying it on the page.
Example:
const username = 'John<script>alert("XSS")</script>'; const encodedUsername = encodeURIComponent(username); // Display encodedUsername on the page
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
Content Security Policy (CSP): Implement Content Security Policy (CSP) to restrict the resources that the browser is allowed to load.
Example:
<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://example.com">
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy