Skip to main content
Version: Next

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.

Classes​

HttpError​

Throw an HttpError from an Operation or API to send an HTTP error response to the client.

For security reasons, Wasp hides the details of any other exception thrown while handling a request: the client gets the generic message for the status code. The status code is 500, unless the error has a valid status or statusCode field, in which case Wasp keeps it, along with the error's headers. In development, Wasp also adds the original message and stack trace to data. The only other errors that keep their message are the ones from the http-errors package (which Express uses) with expose set to true.

The constructor takes:

  • statusCode: The HTTP status code. It must be an integer in the range [400, 600).
  • message (optional): The error message.
  • data (optional): An object with any extra information about the error.
  • options (optional): The standard Error options (e.g. cause), and headers to set on the response.

Wasp sends message and data to the client for every status code, so only put information in them that is safe to show to the user.

When an Operation fails, the client rethrows the error as a WaspHttpError, whose data holds the whole response body, so the data you passed here is at error.data.data. For your custom APIs, pass the error that the api client throws through handleApiError from wasp/client/api to get the same error.

Examples​

import { HttpError } from "wasp/server";

export const getTask = async ({ id }, context) => {
if (!context.user) {
throw new HttpError(401, "You must be logged in.");
}
// ...
};
import { HttpError } from "wasp/server";

throw new HttpError(
429, // status code
"Too many requests", // message
{ limitPerMinute: 60 }, // data
{ headers: { "Retry-After": "60" } }, // options
);

See​

Error handling

Extends​

  • Error

Constructors​

Constructor​

new HttpError(statusCode, message?, data?, options?): HttpError

Parameters​
statusCode​

number

message?​

string

data?​

Record<string, unknown>

options?​

HttpErrorOptions

Returns​

HttpError

Overrides​

Error.constructor

Properties​

data​

data: unknown

headers​

headers: HttpErrorHeaders | undefined

statusCode​

statusCode: number

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​

PrismaClient

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​

Seeding the database


MiddlewareConfigFn​

MiddlewareConfigFn = (middlewareConfig) => MiddlewareConfig

The type of a function that customizes Express middleware. You can pass it to:

  • The server.middlewareConfigFn field of the app spec, to customize the global middleware of all Operations and APIs.
  • The middlewareConfigFn option of an api, to customize the middleware of a single API.
  • The middlewareConfigFn option of an apiNamespace, 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​

MiddlewareConfig

Returns​

MiddlewareConfig

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​

Middleware


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>


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 Express Application. Use it to add custom routes. To change the middleware of Operations and APIs, use MiddlewareConfigFn.
  • server: The Node.js http.Server.

You can also use the function to store values for later use, e.g. a resource your Operations read.

Parameters​

context​

ServerSetupFnContext

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​

const config: ServerConfig

The server's configuration, which Wasp computes from the environment variables.

Example​

import { config } from "wasp/server";

console.log(config.frontendUrl);

See​

Accessing the configuration


env​

const env: 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​


prisma​

const prisma: 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​

HttpErrorOptions​

Extends​

  • ErrorOptions

Properties​

headers?​

optional headers?: HttpErrorHeaders


HttpErrorHeaders​

HttpErrorHeaders = Record<string, string | number | string[]>

The header values Node's response.setHeader accepts, e.g. a list of Set-Cookie values.


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​

Middleware

auth?​

optional auth?: 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​

Wasp server env vars

Properties​

DATABASE_URL​

DATABASE_URL: string

The URL of the database you want your app to use.

DISCORD_CLIENT_ID?​

optional DISCORD_CLIENT_ID?: string

The Discord OAuth client ID. Only present if you use Discord auth.

DISCORD_CLIENT_SECRET?​

optional DISCORD_CLIENT_SECRET?: string

The Discord OAuth client secret. Only present if you use Discord auth.

GITHUB_CLIENT_ID?​

optional GITHUB_CLIENT_ID?: string

The GitHub OAuth client ID. Only present if you use GitHub auth.

GITHUB_CLIENT_SECRET?​

optional GITHUB_CLIENT_SECRET?: string

The GitHub OAuth client secret. Only present if you use GitHub auth.

GOOGLE_CLIENT_ID?​

optional GOOGLE_CLIENT_ID?: string

The Google OAuth client ID. Only present if you use Google auth.

GOOGLE_CLIENT_SECRET?​

optional GOOGLE_CLIENT_SECRET?: string

The Google OAuth client secret. Only present if you use Google auth.

JWT_SECRET?​

optional JWT_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?​

optional KEYCLOAK_CLIENT_ID?: string

The Keycloak OAuth client ID. Only present if you use Keycloak auth.

KEYCLOAK_CLIENT_SECRET?​

optional KEYCLOAK_CLIENT_SECRET?: string

The Keycloak OAuth client secret. Only present if you use Keycloak auth.

KEYCLOAK_REALM_URL?​

optional KEYCLOAK_REALM_URL?: string

The URL of the Keycloak realm. Only present if you use Keycloak auth.

MAILGUN_API_KEY?​

optional MAILGUN_API_KEY?: string

The Mailgun API key. Only present if you use the Mailgun email sender.

MAILGUN_API_URL?​

optional MAILGUN_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?​

optional MAILGUN_DOMAIN?: string

The Mailgun domain. Only present if you use the Mailgun email sender.

MICROSOFT_CLIENT_ID?​

optional MICROSOFT_CLIENT_ID?: string

The Microsoft OAuth client ID. Only present if you use Microsoft auth.

MICROSOFT_CLIENT_SECRET?​

optional MICROSOFT_CLIENT_SECRET?: string

The Microsoft OAuth client secret. Only present if you use Microsoft auth.

MICROSOFT_TENANT_ID?​

optional MICROSOFT_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?​

optional PG_BOSS_NEW_OPTIONS?: string

Custom config for PgBoss, as a JSON env var.

See​

Customizing PgBoss

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?​

optional RESEND_API_KEY?: string

The Resend API key. Only present if you use the Resend email sender.

SENDGRID_API_KEY?​

optional SENDGRID_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?​

optional SLACK_CLIENT_ID?: string

The Slack OAuth client ID. Only present if you use Slack auth.

SLACK_CLIENT_SECRET?​

optional SLACK_CLIENT_SECRET?: string

The Slack OAuth client secret. Only present if you use Slack auth.

SMTP_HOST?​

optional SMTP_HOST?: string

The SMTP server host. Only present if you use the SMTP email sender.

SMTP_PASSWORD?​

optional SMTP_PASSWORD?: string

The SMTP server password. Only present if you use the SMTP email sender.

SMTP_PORT?​

optional SMTP_PORT?: number

The SMTP server port. Only present if you use the SMTP email sender.

SMTP_USERNAME?​

optional SMTP_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