Skip to main content
Version: Next

Queries

We'll explain what Queries are and how to use them. If you're looking for a detailed API specification, skip ahead to the API Reference.

You can use Queries to fetch data from the server. They shouldn't modify the server's state. Fetching all comments on a blog post, a list of users that liked a video, information about a single product based on its ID... All of these are perfect use cases for a Query.

tip

Queries are fairly similar to Actions in terms of their API. Therefore, if you're already familiar with Actions, you might find reading the entire guide repetitive.

We instead recommend skipping ahead and only reading the differences between Queries and Actions, and consulting the API Reference as needed.

Working with Queries​

You declare queries in the Wasp file and implement them using NodeJS. Wasp not only runs these queries within the server's context but also creates code that enables you to call them from any part of your codebase, whether it's on the client or server side.

This means you don't have to build an HTTP API for your query, manage server-side request handling, or even deal with client-side response handling and caching. Instead, just concentrate on implementing the business logic inside your query, and let Wasp handle the rest!

To create a Query, you must:

  1. Declare the Query in Wasp using the query spec.
  2. Define the Query's NodeJS implementation.

After completing these two steps, you'll be able to use the Query from any point in your code.

Specifying Queries​

To create a Query in Wasp, we begin with a query spec.

Let's declare two Queries - one to fetch all tasks, and another to fetch tasks based on a filter, such as whether a task is done:

main.wasp.ts
import { app, query } from "@wasp/spec"
import { getAllTasks, getFilteredTasks } from "./src/queries" with { type: "ref" }

export default app({
// ...
spec: [
query(getAllTasks),
query(getFilteredTasks),
],
})

If you want to know about all supported options for the query spec, take a look at the API Reference.

note

When main.wasp.ts needs to point to your code, it uses imports like this:

import { MainPage } from "./src/MainPage" with { type: "ref" }

Notice the with { type: "ref" } part at the end of the import statement. This tells Wasp to treat the import as a reference to your app's code, without running the imported code. For more details and examples, see reference imports.

info

You might have noticed that we told Wasp to import Query implementations that don't yet exist. Don't worry about that for now. We'll write the implementations imported from queries.ts in the next section.

It's a good idea to start with the high-level concept (the Query spec in the Wasp file) and only then deal with the implementation details (the Query's implementation in JavaScript).

After declaring a Wasp Query, Wasp derives the Query's name from the function you pass to query. For example, query(getFilteredTasks) creates a Query named getFilteredTasks.

Two important things then happen:

  • Wasp generates a server-side NodeJS function with the Query's name.

  • Wasp generates a client-side JavaScript function with the Query's name (e.g., getFilteredTasks). This function takes at most one argument: any serializable data you wish to use inside the Query (usually an object). Wasp will send this data over the network and pass it into the Query's implementation as its first positional argument (more on this when we look at the implementations). Such an abstraction works thanks to an HTTP API route handler Wasp generates on the server, which calls the Query's NodeJS implementation under the hood.

Generating these two functions ensures a similar calling interface across the entire app (both client and server).

Implementing Queries in Node​

Now that we've declared the Query, what remains is to implement it. We've instructed Wasp to look for the Queries' implementations in the file src/queries.ts, so that's where we should export them from.

Here's how you might implement the previously declared Queries getAllTasks and getFilteredTasks:

src/queries.js
// our "database"
const tasks = [
{ id: 1, description: "Buy some eggs", isDone: true },
{ id: 2, description: "Make an omelette", isDone: false },
{ id: 3, description: "Eat breakfast", isDone: false },
]

// You don't need to use the arguments if you don't need them
export const getAllTasks = () => {
return tasks
}

// The 'args' object is something sent by the caller (most often from the client)
export const getFilteredTasks = (args) => {
const { isDone } = args
return tasks.filter((task) => task.isDone === isDone)
}
Payload constraints

Wasp uses superjson under the hood. This means you're not limited to only sending and receiving JSON payloads.

Wasp will automatically handle the serialization and deserialization for all the data types that superjson supports (like biging, Date, Map, Set, etc.), and for Prisma.Decimal.

As long as you're annotating your Operations with the correct automatically generated types, TypeScript ensures your payloads are valid (i.e., Wasp knows how to serialize and deserialize them).

For a detailed explanation of the Query definition API (more precisely, its arguments and return values), check the API Reference.

Using Queries​

Using Queries on the client​

To call a Query on the client, you can import it from wasp/client/operations and call it directly.

The usage doesn't change depending on whether the Query is authenticated or not. Wasp authenticates the logged-in user in the background.

import { getAllTasks, getFilteredTasks } from "wasp/client/operations"

// ...

const allTasks = await getAllTasks()
const doneTasks = await getFilteredTasks({ isDone: true })

Using Queries on the server​

Calling a Query on the server is similar to calling it on the client.

Here's what you have to do differently:

  • Import Queries from wasp/server/operations instead of wasp/client/operations.
  • Make sure you pass in a context object with the user field to authenticated Queries.
    • Note that you don't have to pass other parts of the context object, like Entities, those will get injected automatically.
import { getAllTasks, getFilteredTasks } from "wasp/server/operations"


const user = // Get an AuthUser object, e.g., from context.user in an operation.

// ...

const allTasks = await getAllTasks({ user })
const doneTasks = await getFilteredTasks({ isDone: true }, { user })

The useQuery hook​

When using Queries on the client, you can make them reactive with the useQuery hook. This hook comes bundled with Wasp and is a thin wrapper around the useQuery hook from react-query. The only difference is that you don't need to supply the key - Wasp handles this for you automatically.

Here's an example of calling the Queries using the useQuery hook:

src/MainPage.jsx
import React from "react"
import { useQuery, getAllTasks, getFilteredTasks } from "wasp/client/operations"

const MainPage = () => {
const { data: allTasks, error: error1 } = useQuery(getAllTasks)
const { data: doneTasks, error: error2 } = useQuery(getFilteredTasks, {
isDone: true,
})

if (error1 !== null || error2 !== null) {
return <div>There was an error</div>
}

return (
<div>
<h2>All Tasks</h2>
{allTasks && allTasks.length > 0
? allTasks.map((task) => <Task key={task.id} {...task} />)
: "No tasks"}

<h2>Finished Tasks</h2>
{doneTasks && doneTasks.length > 0
? doneTasks.map((task) => <Task key={task.id} {...task} />)
: "No finished tasks"}
</div>
)
}

const Task = ({ description, isDone }) => {
return (
<div>
<p>
<strong>Description: </strong>
{description}
</p>
<p>
<strong>Is done: </strong>
{isDone ? "Yes" : "No"}
</p>
</div>
)
}

export default MainPage

For a detailed specification of the useQuery hook, check the API Reference.

Error Handling​

When your Query's NodeJS implementation throws an error, Wasp checks what kind of error it is, in this order:

  1. If it is an HttpError, the client receives the error as is, with its status code, message, and data.
  2. If it has a valid status or statusCode field, like the http-errors errors that Express middleware throw, the client receives the closest HttpError Wasp can build from it. Its message is replaced with a generic one, unless the error explicitly allows showing it (e.g. with the expose field of http-errors).
  3. If it is anything else, the client receives a generic 500 Internal Server Error.

In the last two cases, Wasp hides the error's details, so you don't leak sensitive information by accident. The exception is development, where the response also includes the error's message and stack to help you debug. Wasp also logs these errors on the server when their status code is 500 or above.

To send error details to the client, throw an HttpError:

src/queries.js
import { HttpError } from "wasp/errors"

export const getAllTasks = async (args, context) => {
throw new HttpError(403, "You can't do this!", { data: { foo: "bar" } })
}

To also set response headers, e.g. Retry-After, pass headers in the options:

throw new HttpError(429, "Too many requests", { headers: { "Retry-After": "60" } })

Only put information in an HttpError that is safe to show to the user.

On the client, the failed Query throws an HttpError with the same status code, message, and data. Other unexpected failures, like a network error, throw generic Error instances, so make sure the error is an instance of HttpError before reading these fields:

src/MainPage.jsx
import { getAllTasks, useQuery } from "wasp/client/operations";
import { HttpError } from "wasp/errors";

export const MainPage = () => {
const { data: tasks, error } = useQuery(getAllTasks);

if (error instanceof HttpError && error.status === 403) {
return <div>{error.message}</div>;
}
// ...
};

Reading the Error's Request and Response​

On the client, an HttpError also has the Response that the server sent. Use it when you need more than the status code, message, and data, for example to read a response header:

if (error instanceof HttpError && error.status === 429) {
const retryAfter = error.response.headers.get("Retry-After");
}

The body of the Response is already read into message and data, so don't read it again.

To look at the Request that failed, use error.cause.request. The cause is the error that ky, the HTTP client Wasp uses, threw.

When a Query fails, useQuery retries it a few times before giving up. Client errors like 401 or 404 are the exception: retrying won't change the result, so useQuery reports them right away. 408 and 429 are still retried, since they can succeed on a later attempt. To change this, set retry for a single Query or for all Queries.

Using Entities in Queries​

In most cases, resources used in Queries will be Entities. To use an Entity in your Query, add it to the query spec in Wasp:

main.wasp.ts
import { app, query } from "@wasp/spec"
import { getAllTasks, getFilteredTasks } from "./src/queries" with { type: "ref" }

export default app({
// ...
spec: [
query(getAllTasks, { entities: ["Task"] }),
query(getFilteredTasks, { entities: ["Task"] }),
],
})

Wasp will inject the specified Entity into the Query's context argument, giving you access to the Entity's Prisma API:

src/queries.js
export const getAllTasks = async (args, context) => {
return context.entities.Task.findMany({})
}

export const getFilteredTasks = async (args, context) => {
return context.entities.Task.findMany({
where: { isDone: args.isDone },
})
}

The object context.entities.Task exposes prisma.task from Prisma's CRUD API.

API Reference​

Specifying Queries​

API reference

query »

All the options for declaring a query in the Wasp Spec.

API reference

wasp/client/operations »

The functions Wasp generates for calling your Queries on the client.

API reference

wasp/server/operations »

The functions Wasp generates for calling your Queries on the server, and the types for implementing them.

Implementing Queries​

API reference

AuthenticatedQueryDefinition »

The arguments and return value of a Query's implementation, and the generic type Wasp generates for typing it.

API reference

UnauthenticatedQueryDefinition »

The same, for Queries that don't use auth.

API reference

HttpError »

The error for an HTTP error response, which you throw on the server and read on the client.

The useQuery Hook​

API reference

useQuery »

All the arguments of the useQuery hook.