Senior
How to correctly modify a fetch request for secure transmission of sensitive data?
sobes.tech AI
Answer from AI
To securely transmit sensitive data via fetch requests, it is important to consider several aspects:
- Use HTTPS — to ensure data is transmitted over a secure channel.
- Do not transmit sensitive data in the URL (e.g., in query parameters), as URLs can be logged and visible.
- Send data in the request body, for example, in JSON format.
- Use headers to transmit authorization tokens, such as
Authorization: Bearer <token>. - Handle CORS and CSRF — to prevent attacks.
Example of a secure fetch request with token and data in the body:
fetch('https://api.example.com/secure-data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_access_token'
},
body: JSON.stringify({ sensitiveData: 'value' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Thus, avoid transmitting secrets in the URL, always use HTTPS, and send data in the request body with appropriate headers.