wasp/server
Server-side APIs you can use in your Operations, APIs, Jobs, and server setup code.
You can only import wasp/server in server code.
Type Aliases
DbSeedFn
DbSeedFn = (
prisma) =>Promise<void>
The type of a seed function you list in the db.seeds field of the app
spec.
A seed function is an async function that receives the prisma client and uses it to populate the database with some initial data. Since it's server code, it can import other server code, e.g. your Actions.
Run seed functions with wasp db seed (or wasp db seed <seed-name>).
Parameters
prisma
Returns
Promise<void>
Example
import type { DbSeedFn } from "wasp/server";
export const devSeedSimple: DbSeedFn = async (prisma) => {
await prisma.task.create({
data: { description: "Chase the cat", isDone: false },
});
};
See
MiddlewareConfigFn
MiddlewareConfigFn = (
middlewareConfig) =>MiddlewareConfig
The type of a function that customizes Express middleware. You can pass it to:
- The
server.middlewareConfigFnfield of the app spec, to customize the global middleware of all Operations and APIs. - The
middlewareConfigFnoption of anapi, to customize the middleware of a single API. - The
middlewareConfigFnoption of anapiNamespace, to customize the middleware of all APIs under a path.
It receives the current middleware config, a Map from middleware names to
Express RequestHandlers, and returns the new one. You can add, replace, or
delete entries.
The default global entries are "helmet", "cors", "logger",
"express.json", "express.urlencoded", and "cookieParser".
Treat modifications to global middleware with extreme care, as they affect all Operations and APIs. If you're unsure, use one of the other two options.
Parameters
middlewareConfig
Returns
Example
import cors from "cors";
import { config, type MiddlewareConfigFn } from "wasp/server";
export const serverMiddlewareFn: MiddlewareConfigFn = (middlewareConfig) => {
// Example of adding extra domains to CORS.
middlewareConfig.set(
"cors",
cors({
origin: [
...config.allowedCORSOrigins,
"https://example1.com",
"https://example2.com",
],
}),
);
return middlewareConfig;
};
See
PrismaClient
PrismaClient =
object
The type of prisma.
It's the type of the Prisma Client that Prisma generates from your Prisma
schema (or, if you customize it with db.prismaSetupFn, the type of the
client your function returns). It has one property per model, named after
the model in camelCase (e.g. prisma.task for the Task model), plus
Prisma's $-prefixed methods like $transaction and $queryRaw.
Since it depends on your app's schema, this page only shows the minimal structure every Prisma Client has. See the Prisma Client API reference for the rest.
If your schema has no models, Prisma doesn't generate a client, and this
type (and prisma) is null.
Methods
$connect()
$connect():
Promise<void>
Connects to the database.
Returns
Promise<void>
$disconnect()
$disconnect():
Promise<void>
Disconnects from the database.
Returns
Promise<void>
ServerErrorContext
ServerErrorContext = {
source:"request"; } | {jobName:string;source:"job"; } | {source:"webSocket"; } | {source:"oauth"; } | {source:"startup"; } | {source:"dbSeed"; } | {event:"uncaughtException"|"unhandledRejection";source:"process"; }
Where an unexpected server error happened.
"request": While handling a request to an Operation, API, or auth route."job": In a Job.jobNameis the name of the Job."webSocket": While authenticating a WebSocket connection."oauth": During an OAuth login."startup": While starting the server, after your code has loaded, e.g. inserver.setupFn."dbSeed": In a database seed function, when runningwasp db seed."process": Anywhere else in the server, as an uncaught error or an unhandled promise rejection, e.g. in a timer or while your code loads.eventis the name of the Node.js process event.
ServerOnErrorFn
ServerOnErrorFn = (
error,context) =>void|Promise<void>
The type of the function you pass to the server.onError field of the app
spec. Wasp calls it with every unexpected error on the server, after
logging the error.
It receives the error and the ServerErrorContext it happened in.
- An
HttpErroryou throw while handling a request is not unexpected, so Wasp doesn't call the function for it. - The function can be async. Wasp waits for it only when the server exits
because of the error, and for at most 5 seconds. The server exits after
a
"startup"or"dbSeed"error, and after a"process"error whoseeventisuncaughtException. - If the function throws, Wasp logs that error and keeps running.
Parameters
error
unknown
context
Returns
void | Promise<void>
Example
import type { ServerOnErrorFn } from "wasp/server";
export const onServerError: ServerOnErrorFn = (error, context) => {
errorTracker.capture(error, { source: context.source });
};
See
ServerSetupFn
ServerSetupFn = (
context) =>Promise<void>
The type of the function you pass to the server.setupFn field of the app
spec. Wasp runs it on server start, before the server starts listening for
requests.
It receives an object with:
app: The ExpressApplication. Use it to add custom routes. To change the middleware of Operations and APIs, use MiddlewareConfigFn.server: The Node.jshttp.Server.
You can also use the function to store values for later use, e.g. a resource your Operations read.
Parameters
context
Returns
Promise<void>
Example
Adding a custom route:
import type { Application } from "express";
import type { ServerSetupFn } from "wasp/server";
export const mySetupFunction: ServerSetupFn = async ({ app }) => {
addCustomRoute(app);
};
function addCustomRoute(app: Application) {
app.get("/customRoute", (_req, res) => {
res.send("I am a custom route");
});
}
See
Variables
config
constconfig:ServerConfig
The server's configuration, which Wasp computes from the environment variables.
Example
import { config } from "wasp/server";
console.log(config.frontendUrl);
See
env
constenv:ServerEnv
The validated server environment variables.
Wasp validates process.env on server start against its own validation
schema, merged with the one you define in the server.envValidationSchema
field of the app spec. If validation fails, the server doesn't start.
env contains both Wasp-defined env vars (described in
ServerEnv) and user-defined env vars (the fields of your
validation schema, with the types your schema outputs). It leaves out any
other env var.
You can use process.env.SOME_SECRET directly in your code, but we don't
recommend it, since process.env isn't validated and missing env vars can
cause runtime errors.
Example
import { env } from "wasp/server";
// Wasp-defined
const serverUrl = env.WASP_SERVER_URL;
// User-defined
const stripeApiKey = env.STRIPE_API_KEY;
See
- Server env vars
- Custom env var validations
- defineEnvValidationSchema to define your validation schema.
prisma
constprisma:PrismaClient
The Prisma Client instance
Wasp uses to access the database, e.g. for the entities in your Operations'
context.
We recommend sticking with the Wasp-provided mechanisms, and only using the Prisma Client directly if you need a feature Wasp doesn't provide.
Example
import { prisma } from "wasp/server";
await prisma.task.create({
data: { description: "Read the Entities doc", isDone: true },
});
See
Referenced Types
MiddlewareConfig
MiddlewareConfig =
Map<string,RequestHandler>
ServerConfig
ServerConfig =
object
The type of config.
Properties
allowedCORSOrigins
allowedCORSOrigins: (
string|RegExp)[]
The origins the default CORS middleware allows.
In development, it allows every origin. In production, it only allows
the origin of frontendUrl.
See
auth?
optionalauth?:object
Auth settings. Only present if your app uses auth.
jwtSecret
jwtSecret:
string
The secret for signing tokens, from the JWT_SECRET env var.
databaseUrl
databaseUrl:
string
The URL of the database, from the DATABASE_URL env var.
env
env:
"development"|"production"
The environment the server runs in, from the NODE_ENV env var.
frontendUrl
frontendUrl:
string
The URL of your app's client, without a trailing slash, from the
WASP_WEB_CLIENT_URL env var.
isDevelopment
isDevelopment:
boolean
Whether the server runs in development (wasp start).
port
port:
number
The port the server listens on, from the PORT env var.
serverUrl
serverUrl:
string
The URL of your app's server, without a trailing slash, from the
WASP_SERVER_URL env var.
ServerEnv
ServerEnv =
object
The Wasp-defined env vars in env.
Wasp only includes the env vars of the features your app uses (e.g. the
SMTP_* ones only if you use the SMTP email sender).
See
Properties
DATABASE_URL
DATABASE_URL:
string
The URL of the database you want your app to use.
DISCORD_CLIENT_ID?
optionalDISCORD_CLIENT_ID?:string
The Discord OAuth client ID. Only present if you use Discord auth.
DISCORD_CLIENT_SECRET?
optionalDISCORD_CLIENT_SECRET?:string
The Discord OAuth client secret. Only present if you use Discord auth.
GITHUB_CLIENT_ID?
optionalGITHUB_CLIENT_ID?:string
The GitHub OAuth client ID. Only present if you use GitHub auth.
GITHUB_CLIENT_SECRET?
optionalGITHUB_CLIENT_SECRET?:string
The GitHub OAuth client secret. Only present if you use GitHub auth.
GOOGLE_CLIENT_ID?
optionalGOOGLE_CLIENT_ID?:string
The Google OAuth client ID. Only present if you use Google auth.
GOOGLE_CLIENT_SECRET?
optionalGOOGLE_CLIENT_SECRET?:string
The Google OAuth client secret. Only present if you use Google auth.
JWT_SECRET?
optionalJWT_SECRET?:string
A random string of at least 32 characters, used to generate secure tokens. Only present if your app uses auth.
Defaults to DEVJWTSECRET in development.
KEYCLOAK_CLIENT_ID?
optionalKEYCLOAK_CLIENT_ID?:string
The Keycloak OAuth client ID. Only present if you use Keycloak auth.
KEYCLOAK_CLIENT_SECRET?
optionalKEYCLOAK_CLIENT_SECRET?:string
The Keycloak OAuth client secret. Only present if you use Keycloak auth.
KEYCLOAK_REALM_URL?
optionalKEYCLOAK_REALM_URL?:string
The URL of the Keycloak realm. Only present if you use Keycloak auth.
MAILGUN_API_KEY?
optionalMAILGUN_API_KEY?:string
The Mailgun API key. Only present if you use the Mailgun email sender.
MAILGUN_API_URL?
optionalMAILGUN_API_URL?:string
The Mailgun API URL. Only present if you use the Mailgun email sender and set it.
Useful if you want to use the EU API endpoint
(https://api.eu.mailgun.net).
MAILGUN_DOMAIN?
optionalMAILGUN_DOMAIN?:string
The Mailgun domain. Only present if you use the Mailgun email sender.
MICROSOFT_CLIENT_ID?
optionalMICROSOFT_CLIENT_ID?:string
The Microsoft OAuth client ID. Only present if you use Microsoft auth.
MICROSOFT_CLIENT_SECRET?
optionalMICROSOFT_CLIENT_SECRET?:string
The Microsoft OAuth client secret. Only present if you use Microsoft auth.
MICROSOFT_TENANT_ID?
optionalMICROSOFT_TENANT_ID?:string
The Microsoft tenant ID. Only present if you use Microsoft auth.
NODE_ENV
NODE_ENV:
"development"|"production"
The environment the server runs in.
Default
"development"
PG_BOSS_NEW_OPTIONS?
optionalPG_BOSS_NEW_OPTIONS?:string
Custom config for PgBoss, as a JSON env var.
See
PORT
PORT:
number
The port the server listens on for requests.
Wasp sets this in development, but your deployed app requires it.
RESEND_API_KEY?
optionalRESEND_API_KEY?:string
The Resend API key. Only present if you use the Resend email sender.
SENDGRID_API_KEY?
optionalSENDGRID_API_KEY?:string
The SendGrid API key. Only present if you use the SendGrid email sender.
SKIP_EMAIL_VERIFICATION_IN_DEV
SKIP_EMAIL_VERIFICATION_IN_DEV:
boolean
If true, Wasp automatically sets user emails as verified in
development. Set it to the string "true" or "false".
Default
false
SLACK_CLIENT_ID?
optionalSLACK_CLIENT_ID?:string
The Slack OAuth client ID. Only present if you use Slack auth.
SLACK_CLIENT_SECRET?
optionalSLACK_CLIENT_SECRET?:string
The Slack OAuth client secret. Only present if you use Slack auth.
SMTP_HOST?
optionalSMTP_HOST?:string
The SMTP server host. Only present if you use the SMTP email sender.
SMTP_PASSWORD?
optionalSMTP_PASSWORD?:string
The SMTP server password. Only present if you use the SMTP email sender.
SMTP_PORT?
optionalSMTP_PORT?:number
The SMTP server port. Only present if you use the SMTP email sender.
SMTP_USERNAME?
optionalSMTP_USERNAME?:string
The SMTP server username. Only present if you use the SMTP email sender.
WASP_SERVER_URL
WASP_SERVER_URL:
string
The URL of your app's server. The server uses it in various features, e.g. to redirect users when logging in with OAuth providers like Google or GitHub.
Wasp sets this in development, but your deployed app requires it.
WASP_WEB_CLIENT_URL
WASP_WEB_CLIENT_URL:
string
The URL of your app's client. The server uses it in various features, e.g. linking to your app in emails.
Wasp sets this in development, but your deployed app requires it.
ServerSetupFnContext
ServerSetupFnContext =
object
Properties
app
app:
Application
server
server:
Server