Validate incoming data, and respond in the user's language
While there are libraries that help us both translate messages, and validate data in an Express' server, doing both can be a bit tricky.
I created this example based on a project I recently did for an API which had to be fully translated to both English and Spanish.
- Checks the header, accepting either es_MX or en_US (which is also the default)
- Validates both the existence of the expected fields, and the validity of the data being sent to the API
- Returns either error or success messages in the user's defined language (Spanish or English at this moment)
- Postman or similar software
Check out this guide for a more thorough reading, or jump straight ahead for more concise instructions.
Live API:
https://express-i18n-api.herokuapp.com/
Express listens on
/api/login
and/api/forgot-password
login expectspassword
; forgot-password only an
Remember to set your headers to es_MX to see it in action in Spanish
Clone the repo, then install dependencies:
git clone https://github.com/israelmuca/express-i18n-api.git myproject
cd myproject
npm i
Run the API:
npm run start
The console should read:
App running on port 8080
While the API is running, you can also run tests with:
npm run test
Or, you can jump straight into Postman:
- Set the Method to POST
- Set the Request URL to localhost:8080/api/login or localhost:8080/api/forgot-password
- Set the Headers key to Accept-Language and the value to es_MX or en_US
The login
endpoint requires email
and password
. The only validation that is done is that both fields exists, and the email is a valid email address ([email protected]).
The forgot-password
endpoint requires email
. It only validates the email is valid.