Secure coding
- React Native course
- Expert
- Lesson 41/47
- 5 min
Learn secure coding principles.
Secure coding principles
Secure coding means thinking about security while writing code; not adding it later. Core principles: validate input, escape output, give least privilege, do not leak error messages.
In React Native user input comes from TextInput. Validate this input before using it: is the email format right, is the length over the limit? Escape it before sending to an API. Do not give internal server paths in error messages; show a general message. Do not log sensitive data to console.log; even with logs off in production it creates risk. These principles shrink the attack surface.
An input validation example
To validate an email input you check its format. A simple method: const emailOk = /[^@]+@[^@]+\.[^@]+/.test(email). This checks whether the email has an @ and a dot.
Stricter validation uses a library; but basic format checks stop most attacks. Length is also bounded: if (email.length > 200) return;. This makes buffer attacks with very long input harder. Validation is done both on the client and the server; the client can be skipped, the server cannot.
Practice Write an input validation function
Write a validateEmail function. It takes an email parameter. It tests with the /.+@.+\..+/ regex and returns a boolean.
Starter code
// Add the validateEmail function hereSample solution
function validateEmail(email) {
return /.+@.+\..+/.test(email);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What should be done with user input?
<TextInput value={text} />- It should be validated Correct answer
- It should go straight to the database
- It should be logged
- It should be ignored
Explanation: Input must be validated before use.
2 Match each principle to its role
| Term | Meaning |
|---|---|
validate input |
Format and length |
escape output |
Stops injection |
least privilege |
Limited access |
hide errors |
No internal paths |
3 Email validation
const emailOk = /[^@]+____@[^@]+\.[^@]+/.test(email);
const emailOk = /[^@]+@@[^@]+\.[^@]+/.test(email);
Explanation: @ is the separator in an email address.