Miscellaneous
Ajv JSON Schema Validator
Ajv, one of the best JSON schema validators, is
extremely useful in the development of backend APIs for data validation. But Ajv
is not supported by many edge environments, including Vercel, because of it's
usage of eval
. However, the SherpaJS compiler will pre-compile standalone Ajv
schema, so schema validation can be done on the edge.
Example Static Schema
Start by creating a schema.json
file containing the desired schema.
{
"type": "object",
"properties": {
"foo": {
"type": "number"
}
},
"required": ["foo"],
"additionalProperties": false
}
Then import your schema (in any script), and write the schema in the AJV
function, provided by Sherpa Core.
import { Request, Response, AJV } from "sherpa-core";
import schemaFoo from "../../src/foo.schema.json";
const validatorFoo = AJV(schemaFoo);
export function POST(request:Request) {
try {
if (!validatorFoo(request.body)) {
return Response.text(JSON.stringify(validatorFoo.errors));
}
return Response.text("OK");
} catch (e) {
console.log(e);
return Response.text(e.toString());
}
}
Environment Variables
Environment variables are a key part of configuring your SherpaJS application. They allow you to set various configuration options and secrets without hardcoding them into your application's codebase.
Loading Environment Variables
SherpaJS uses the .env
file to load environment variables. This file should
be placed at the root of your project. When the system is compiled, the
variables defined in this file are automatically loaded into your server's
environment.
Any environment variables provided by hosting services (such as Vercel or AWS) are automatically included in your build.
Environment varibles can also be added during build with the build command.
Automatic Parsing
SherpaJS automatically parses environment variables to their appropriate types:
- Strings remain as strings
- Booleans are converted to
true
orfalse
- Numbers are converted to numeric values
Example .env File
Here is an example of a .env
file:
PORT=3000 # number
DATABASE_URL=mongodb://localhost:27017/mydatabase # string
JWT_SECRET=myverysecretkey # string
ENABLE_FEATURE_X=true # boolean
MAX_CONNECTIONS=100 # number
Best Practices
- Security: Never commit your
.env
file to version control. Add it to your.gitignore
file. - Defaults: Provide sensible default values for environment variables in your code.
- Validation: Validate the presence and format of critical environment variables at the start of your application to avoid runtime errors.