Express i18n API
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.
Test API without installing anything:
Express listens on
password; forgot-password only an
Remember to set your headers to es_MX to see it in action in Spanish
Run the code locally
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:
Test with 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
login endpoint requires
password. The only validation that is done is that both fields exists, and the email is a valid email address (email@example.com).
forgot-password endpoint requires