Skip to main content
Version: 2.x

GraphQL

GraphQL is a fundamental part of Redwood. Having said that, you can get going without knowing anything about it, and can actually get quite far without ever having to read the docs. But to master Redwood, you'll need to have more than just a vague notion of what GraphQL is. You'll have to really grok it.

The good thing is that, besides taking care of the annoying stuff for you (namely, mapping your resolvers, which gets annoying fast if you do it yourself!), there's not many gotchas with GraphQL in Redwood. GraphQL is GraphQL. The only Redwood-specific thing you should really be aware of is resolver args.

Since there's two parts to GraphQL in Redwood, the client and the server, we've divided this doc up that way.

On the web side, Redwood uses Apollo Client by default though you can swap it out for something else if you want.

The api side offers a GraphQL server built on GraphQL Yoga and the Envelop plugin system from The Guild.

Redwood's api side is "serverless first", meaning it's architected as functions which can be deployed on either serverless or traditional infrastructure, and Redwood's GraphQL endpoint is effectively "just another function" (with a whole lot more going on under the hood, but that part is handled for you, out of the box). One of the tenets of the Redwood philosophy is "Redwood believes that, as much as possible, you should be able to operate in a serverless mindset and deploy to a generic computational grid.”

To be able to deploy to a “generic computation grid” means that, as a developer, you should be able to deploy using the provider or technology of your choosing. You should be able to deploy to Netlify, Vercel, Fly, Render, AWS Serverless, or elsewhere with ease and no vendor or platform lock in. You should be in control of the framework, what the response looks like, and how your clients consume it.

The same should be true of your GraphQL Server. GraphQL Yoga makes that possible.

Existing libraries like Apollo Server provide you with either a complete HTTP server or a middleware function that you can plug into your framework of choice. GraphQL Yoga takes a different approach—it just provides a handful of functions that you can use to turn an HTTP request into a GraphQL execution result. In other words, GraphQL Yoga leaves it up to you to decide how to send back the response.

We leverage Envelop plugins to provide GraphQL security best practices and implement custom internal plugins to help with authentication, logging, directive handling, and more.

All this gets us closer to Redwood's goal of being able to deploy to a "generic computation grid". And that’s exciting!

Client-side

RedwoodApolloProvider

By default, Redwood Apps come ready-to-query with the RedwoodApolloProvider. As you can tell from the name, this Provider wraps ApolloProvider. Omitting a few things, this is what you'll normally see in Redwood Apps:

web/src/App.js
import { RedwoodApolloProvider } from '@redwoodjs/web/apollo'

// ...

const App = () => (
<RedwoodApolloProvider>
<Routes />
</RedwoodApolloProvider>
)

// ...

You can use Apollo's useQuery and useMutation hooks by importing them from @redwoodjs/web, though if you're using useQuery, we recommend that you use a Cell:

web/src/components/MutateButton.js
import { useMutation } from '@redwoodjs/web'

const MUTATION = gql`
# your mutation...
`

const MutateButton = () => {
const [mutate] = useMutation(MUTATION)

return (
<button onClick={() => mutate({ ... })}>
Click to mutate
</button>
)
}

Note that you're free to use any of Apollo's other hooks, you'll just have to import them from @apollo/client instead. In particular, these two hooks might come in handy:

HookDescription
useLazyQueryExecute queries in response to events other than component rendering
useApolloClientAccess your instance of ApolloClient

Customizing the Apollo Client and Cache

By default, RedwoodApolloProvider configures an ApolloClient instance with 1) a default instance of InMemoryCache to cache responses from the GraphQL API and 2) an authMiddleware to sign API requests for use with Redwood's built-in auth. Beyond the cache and link params, which are used to set up that functionality, you can specify additional params to be passed to ApolloClient using the graphQLClientConfig prop. The full list of available configuration options for the client are documented here on Apollo's site.

Depending on your use case, you may want to configure InMemoryCache. For example, you may need to specify a type policy to change the key by which a model is cached or to enable pagination on a query. This article from Apollo explains in further detail why and how you might want to do this.

To configure the cache when it's created, use the cacheConfig property on graphQLClientConfig. Any value you pass is passed directly to InMemoryCache when it's created.

For example, if you have a query named search that supports Apollo's offset pagination, you could enable it by specifying:

<RedwoodApolloProvider graphQLClientConfig={{
cacheConfig: {
typePolicies: {
Query: {
fields: {
search: {
// Uses the offsetLimitPagination preset from "@apollo/client/utilities";
...offsetLimitPagination()
}
}
}
}
}
}}>

Swapping out the RedwoodApolloProvider

As long as you're willing to do a bit of configuring yourself, you can swap out RedwoodApolloProvider with your GraphQL Client of choice. You'll just have to get to know a bit of the make up of the RedwoodApolloProvider; it's actually composed of a few more Providers and hooks:

  • FetchConfigProvider
  • useFetchConfig
  • GraphQLHooksProvider

For an example of configuring your own GraphQL Client, see the redwoodjs-react-query-provider. If you were thinking about using react-query, you can also just go ahead and install it!

Note that if you don't import RedwoodApolloProvider, it won't be included in your bundle, dropping your bundle size quite a lot!

Server-side

Understanding Default Resolvers

According to the spec, for every field in your sdl, there has to be a resolver in your Services. But you'll usually see fewer resolvers in your Services than you technically should. And that's because if you don't define a resolver, GraphQL Yoga server will.

The key question the Yoga server asks is: "Does the parent argument (in Redwood apps, the parent argument is named rootsee Redwood's Resolver Args) have a property with this resolver's exact name?" Most of the time, especially with Prisma Client's ergonomic returns, the answer is yes.

Let's walk through an example. Say our sdl looks like this:

api/src/graphql/user.sdl.js
export const schema = gql`
type User {
id: Int!
email: String!
name: String
}

type Query {
users: [User!]!
}
`

So we have a User model in our schema.prisma that looks like this:

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}

If you create your Services for this model using Redwood's generator (yarn rw g service user), your Services will look like this:

api/src/services/user/user.js
import { db } from 'src/lib/db'

export const users = () => {
return db.user.findMany()
}

Which begs the question: where are the resolvers for the User fieldsid, email, and name? All we have is the resolver for the Query field, users.

As we just mentioned, GraphQL Yoga defines them for you. And since the root argument for id, email, and name has a property with each resolvers' exact name (i.e. root.id, root.email, root.name), it'll return the property's value (instead of returning undefined, which is what Yoga would do if that weren't the case).

But, if you wanted to be explicit about it, this is what it would look like:

api/src/services/user/user.js
import { db } from 'src/lib/db'

export const users = () => {
return db.user.findMany()
}

export const Users = {
id: (_args, { root }) => root.id,
email: (_args, { root }) => root.email,
name: (_args, { root }) => root.name,
}

The terminological way of saying this is, to create a resolver for a field on a type, in the Service, export an object with the same name as the type that has a property with the same name as the field.

Sometimes you want to do this since you can do things like add completely custom fields this way:

export const Users = {
id: (_args, { root }) => root.id,
email: (_args, { root }) => root.email,
name: (_args, { root }) => root.name,
age: (_args, { root }) => new Date().getFullYear() - root.birthDate.getFullYear()
}

Redwood's Resolver Args

According to the spec, resolvers take four arguments: args, obj, context, and info. In Redwood, resolvers do take these four arguments, but what they're named and how they're passed to resolvers is slightly different:

  • args is passed as the first argument
  • obj is named root (all the rest keep their names)
  • root, context, and info are wrapped into an object; this object is passed as the second argument

Here's an example to make things clear:

export const Post = {
user: (args, { root, context, info }) => db.post.findUnique({ where: { id: root.id } }).user(),
}

Of the four, you'll see args and root being used a lot.

ArgumentDescription
argsThe arguments provided to the field in the GraphQL query
rootThe previous return in the resolver chain
contextHolds important contextual information, like the currently logged in user
infoHolds field-specific information relevant to the current query as well as the schema details

There's so many terms!

Half the battle here is really just coming to terms. To keep your head from spinning, keep in mind that everybody tends to rename obj to something else: Redwood calls it root, GraphQL Yoga calls it parent. obj isn't exactly the most descriptive name in the world.

Context

In Redwood, the context object that's passed to resolvers is actually available to all your Services, whether or not they're serving as resolvers. Just import it from @redwoodjs/graphql-server:

import { context } from '@redwoodjs/graphql-server'

How to Modify the Context

Because the context is read-only in your services, if you need to modify it, then you need to do so in the createGraphQLHandler.

To populate or enrich the context on a per-request basis with additional attributes, set the context attribute createGraphQLHandler to a custom ContextFunction that modifies the context.

For example, if we want to populate a new, custom ipAddress attribute on the context with the information from the request's event, declare the setIpAddress ContextFunction as seen here:

api/src/functions/graphql.js
// ...

const ipAddress = ({ event }) => {
return event?.headers?.['client-ip'] || event?.requestContext?.identity?.sourceIp || 'localhost'
}

const setIpAddress = async ({ event, context }) => {
context.ipAddress = ipAddress({ event })
}

export const handler = createGraphQLHandler({
getCurrentUser,
loggerConfig: {
logger,
options: { operationName: true, tracing: true },
},
schema: makeMergedSchema({
schemas,
services,
}),
context: setIpAddress,
onException: () => {
// Disconnect from your database with an unhandled exception.
db.$disconnect()
},
})

Note: If you use the preview GraphQL Yoga/Envelop graphql-server package and a custom ContextFunction to modify the context in the createGraphQL handler, the function is provided only the context and not the event. However, the event information is available as an attribute of the context as context.event. Therefore, in the above example, one would fetch the ip address from the event this way: ipAddress({ event: context.event }).

The Root Schema

Did you know that you can query redwood? Try it in the GraphQL Playground (you can find the GraphQL Playground at http://localhost:8911/graphql when your dev server is runningyarn rw dev api):

query {
redwood {
version
currentUser
}
}

How is this possible? Via Redwood's root schema. The root schema is where things like currentUser are defined.

Now that you've seen the sdl, be sure to check out the resolvers.

CORS Configuration

CORS stands for Cross Origin Resource Sharing; in a nutshell, by default, browsers aren't allowed to access resources outside their own domain.

Let's say you're hosting each of your Redwood app's sides on different domains: the web side on www.example.com and the api side (and thus, the GraphQL Server) on api.example.com. When the browser tries to fetch data from the /graphql function, you'll see an error that says the request was blocked due to CORS. Wording may vary, but it'll be similar to:

⛔️ Access to fetch ... has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

To fix this, you need to "configure CORS" by adding:

'Access-Control-Allow-Origin': 'https://example.com'
'Access-Control-Allow-Credentials': true

to the GraphQL response headers which you can do this by setting the cors option in api/src/functions/graphql.{js|t}s:

export const handler = createGraphQLHandler({
loggerConfig: { logger, options: {} },
directives,
sdls,
services,
cors: {
// 👈 setup your CORS configuration options
origin: '*',
credentials: true,
},
onException: () => {
// Disconnect from your database with an unhandled exception.
db.$disconnect()
},
})

For more in-depth discussion and configuration of CORS when it comes to using a cookie-based auth system (like dbAuth), see the CORS documentation.

Health Checks

Health checks are used determine if a server is available and ready to start serving traffic. By default, Redwood's GraphQLHandler provides a health check endpoint at /graphql/health which returns a 200 status code with a result of { status: 'pass' } if the server is healthy and can accept requests or a 503 status code with { status: fail } if not.

If you need more than the default basic health check, you can provide a custom implementation via an onHealthCheck function when creating the GraphQLHandler. If defined, this async onHealthCheck function should return if the server is deemed ready or throw if there is an error.

api/src/functions/graphql.{ts,js}
const myCustomHealthCheck = async () => {
if (ok) {
// Implement your custom check, such as:
// * invoke an api
// * call a service
// * make a db request
// that ensures your GraphQL endpoint is healthy
return
}

throw Error('Health check failed')
}

export const handler = createGraphQLHandler({
onHealthCheck = await myCustomHealthCheck(),
// .. other config
getCurrentUser,
directives,
sdls,
services,
})

Perform a Health Check

To perform a health check, make a HTTP GET request to the /graphql/health endpoint.

For local development, with the proxy using curl from the command line:

curl http://localhost:8910/.redwood/functions/graphql/health

or by directly invoking the graphql function:

curl http://localhost:8911/graphql/health

you should get the response:

{ "status": "pass" }

For production or your deploy, make a request wherever your /graphql function exists.

Note: These examples use curl but you can performa a health check via any HTTP GET request.

Verifying GraphQL Schema

In order to keep your GraphQL endpoint and services secure, you must specify one of @requireAuth, @skipAuth or a custom directive on every query and mutation defined in your SDL.

Redwood will verify that your schema complies with these runs when:

  • building (or building just the api)
  • launching the dev server.

If any fail this check, you will see:

  • each query of mutation listed in the command's error log
  • a fatal error ⚠️ GraphQL server crashed if launching the server

Build-time Verification

When building via the yarn rw build command and the SDL fails verification, you will see output that lists each query or mutation missing the directive:

  ✔ Generating Prisma Client...
✖ Verifying graphql schema...
→ - deletePost Mutation
Building API...
Cleaning Web...
Building Web...
Prerendering Web...

You must specify one of @requireAuth, @skipAuth or a custom directive for
- contacts Query
- posts Query
- post Query
- createContact Mutation
- createPost Mutation
- updatePost Mutation
- deletePost Mutation

Dev Server Verification

When launching the dev server via the yarn rw dev command, you will see output that lists each query or mutation missing the directive:


gen | Generating TypeScript definitions and GraphQL schemas...
gen | 37 files generated
api | Building... Took 444 ms
api | Starting API Server... Took 2 ms
api | Listening on http://localhost:8911/
api | Importing Server Functions...
web | ...
api | FATAL [2021-09-24 18:41:49.700 +0000]:
api | ⚠️ GraphQL server crashed
api |
api | Error: You must specify one of @requireAuth, @skipAuth or a custom directive for
api | - contacts Query
api | - posts Query
api | - post Query
api | - createContact Mutation
api | - createPost Mutation
api | - updatePost Mutation
api | - deletePost Mutation

To fix these errors, simple declare with @requireAuth to enforce authentication or @skipAuth to keep the operation public on each as appropriate for your app's permissions needs.

Custom Scalars

GraphQL scalar types give data meaning and validate that their values makes sense. Out of the box, GraphQL comes with Int, Float, String, Boolean and ID. While those can cover a wide variety of use cases, you may need more specific scalar types to better describe and validate your application's data.

For example, if there's a Person type in your schema that has a field like ageInYears, if it's actually supposed to represent a person's age, technically it should only be a positive integer—never a negative one. Something like the PositiveInt scalar provides that meaning and validation.

Scalars vs Service vs Directives

How are custom scalars different from Service Validations or Validator Directives?

Service validations run when resolving the service. Because they run at the start of your Service function and throw if conditions aren't met, they're great for validating whenever you use a Service—anywhere, anytime. For example, they'll validate via GraphQL, Serverless Functions, webhooks, etc. Custom scalars, however, only validate via GraphQL and not anywhere else.

Service validations also perform more fine-grained checks than scalars which are more geared toward validating that data is of a specific type.

Validator Directives control user access to data and also whether or not a user is authorized to perform certain queries and/or mutations.

How To Add a Custom Scalar

Let's say that you have a Product type that has three fields: a name, a description, and the type of currency. The built-in String scalar should suffice for the first two, but for the third, you'd be better off with a more-specific String scalar that only accepts ISO 4217 currency codes, like USD, EUR, CAD, etc. Luckily there's already a Currency scalar type that does exactly that! All you have to do is add it to your GraphQL schema.

To add a custom scalar to your GraphQL schema:

  1. Add the scalar definition to one of your sdl files, such as api/src/graphql/scalars.sdl.ts

Note that you may have to create this file. Moreover, it's just a convention—custom scalar type definitions can be in any of your sdl files.

api/src/graphql/scalars.sdl.ts
export const schema = gql`
scalar Currency
`

  1. Import the scalar's definition and resolver and pass them to your GraphQLHandler via the schemaOptions property:
api/src/functions/graphql.ts
import { CurrencyDefinition, CurrencyResolver } from 'graphql-scalars'

// ...

export const handler = createGraphQLHandler({
loggerConfig: { logger, options: {} },
directives,
sdls,
services,
schemaOptions: {
typeDefs: [CurrencyDefinition],
resolvers: { Currency: CurrencyResolver },
},
onException: () => {
// Disconnect from your database with an unhandled exception.
db.$disconnect()
},
})

  1. Use the scalar in your types
export const schema = gql`
type Product {
id: Int!
name: String!
description: String!
currency_iso_4217: Currency! // validate on query
createdAt: DateTime!
}

type Query {
posts: [Product!]! @requireAuth
post(id: Int!): Product @requireAuth
}

input CreateProductInput {
name: String!
description: String!
currency_iso_4217: Currency! // validate on mutation
}

input UpdateProductInput {
name: String
description: String
currency_iso_4217: Currency // validate on mutation
}

type Mutation {
createProduct(input: CreateProductInput!): Product! @requireAuth
updateProduct(id: Int!, input: UpdateProductInput!): Product! @requireAuth
deleteProduct(id: Int!): Product! @requireAuth
}
`

Directives

Directives supercharge your GraphQL services. They add configuration to fields, types or operations that act like "middleware" that lets you run reusable code during GraphQL execution to perform tasks like authentication, formatting, and more.

You'll recognize a directive by its preceded by the @ character, e.g. @myDirective, and by being declared alongside a field:

type Bar {
name: String! @myDirective
}

or a Query or Mutation:

type Query {
bars: [Bar!]! @myDirective
}

type Mutation {
createBar(input: CreateBarInput!): Bar! @myDirective
}

Unions

Unions are abstract GraphQL types that enable a schema field to return one of multiple object types.

union FavoriteTree = Redwood | Ginkgo | Oak

A field can have a union as its return type.

type Query {
searchTrees: [FavoriteTree] // This list can include Redwood, Gingko or Oak objects
}

All of a union's included types must be object types and do not need to share any fields.

To query a union, you can take advantage on inline fragments to include subfields of multiple possible types.

query GetFavoriteTrees {
__typename // typename is helpful when querying a field that returns one of multiple types
searchTrees {
... on Redwood {
name
height
}
... on Ginkgo {
name
medicalUse
}
... on Oak {
name
acornType
}
}
}

Redwood will automatically detect your union types in your sdl files and resolve which of your union's types is being returned. If the returned object does not match any of the valid types, the associated operation will produce a GraphQL error.

GraphQL Handler Setup

Redwood makes it easy to code, organize, and map your directives into the GraphQL schema.

You simply add them to the directives directory and the createGraphQLHandler will do all the work.

api/src/functions/graphql.ts
import { createGraphQLHandler } from '@redwoodjs/graphql-server'

import directives from 'src/directives/**/*.{js,ts}' // 👈 directives live here
import sdls from 'src/graphql/**/*.sdl.{js,ts}'
import services from 'src/services/**/*.{js,ts}'

import { db } from 'src/lib/db'
import { logger } from 'src/lib/logger'

export const handler = createGraphQLHandler({
loggerConfig: { logger, options: {} },
directives, // 👈 directives are added to the schema here
sdls,
services,
onException: () => {
// Disconnect from your database with an unhandled exception.
db.$disconnect()
},
})

Note: Check-out the in-depth look at Redwood Directives that explains how to generate directives so you may use them to validate access and transform the response.

Logging

Logging is essential in production apps to be alerted about critical errors and to be able to respond effectively to support issues. In staging and development environments, logging helps you debug queries, resolvers and cell requests.

We want to make logging simple when using RedwoodJS and therefore have configured the api-side GraphQL handler to log common information about your queries and mutations. Log statements also be optionally enriched with operation names, user agents, request ids, and performance timings to give you move visibility into your GraphQL api.

By configuring the GraphQL handler to use your api side RedwoodJS logger, any errors and other log statements about the GraphQL execution will be logged to the destination you've set up: to standard output, file, or transport stream.

You configure the logger using the loggerConfig that accepts a logger and a set of GraphQL Logger Options.

Configure the GraphQL Logger

A typical GraphQLHandler graphql.ts is as follows:

api/src/functions/graphql.ts
// ...

import { logger } from 'src/lib/logger'

// ...
export const handler = createGraphQLHandler({
loggerConfig: { logger, options: {} },
// ...
})

Log Common Information

The loggerConfig takes several options that logs meaningful information along the graphQL execution lifecycle.

OptionDescription
dataInclude response data sent to client.
operationNameInclude operation name. The operation name is a meaningful and explicit name for your operation. It is only required in multi-operation documents, but its use is encouraged because it is very helpful for debugging and server-side logging. When something goes wrong (you see errors either in your network logs, or in the logs of your GraphQL server) it is easier to identify a query in your codebase by name instead of trying to decipher the contents. Think of this just like a function name in your favorite programming language. See https://graphql.org/learn/queries/#operation-name
requestIdInclude the event's requestId, or if none, generate a uuid as an identifier.
queryInclude the query. This is the query or mutation (with fields) made in the request.
tracingInclude the tracing and timing information. This will log various performance timings within the GraphQL event lifecycle (parsing, validating, executing, etc).
userAgentInclude the browser (or client's) user agent. This can be helpful to know what type of client made the request to resolve issues when encountering errors or unexpected behavior.

Therefore, if you wish to log the GraphQL query made, the data returned, and the operationName used, you would

api/src/functions/graphql.ts
export const handler = createGraphQLHandler({
loggerConfig: {
logger,
options: { data: true, operationName: true, query: true },
},
// ...
})

Exclude Operations

You can exclude GraphQL operations by name with excludeOperations. This is useful when you want to filter out certain operations from the log output, for example, IntrospectionQuery from GraphQL playground:

api/src/functions/graphql.ts
export const handler = createGraphQLHandler({
loggerConfig: {
logger,
options: { excludeOperations: ['IntrospectionQuery'] },
},
directives,
sdls,
services,
onException: () => {
// Disconnect from your database with an unhandled exception.
db.$disconnect()
},
})

Relevant anatomy of an operation

In the example below, "FilteredQuery" is the operation's name. That's what you'd pass to excludeOperations if you wanted it filtered out.

export const filteredQuery = `
query FilteredQuery {
me {
id
name
}
}

Benefits of Logging

Benefits of logging common GraphQL request information include debugging, profiling, and resolving issue reports.

Operation Name Identifies Cells

The operation name is a meaningful and explicit name for your operation. It is only required in multi-operation documents, but its use is encouraged because it is very helpful for debugging and server-side logging.

Because your cell typically has a unique operation name, logging this can help you identify which cell made a request.

api/src/functions/graphql.ts
// ...
export const handler = createGraphQLHandler({
loggerConfig: { logger, options: { operationName: true } },
// ...

RequestId for Support Issue Resolution

Often times, your deployment provider will provide a request identifier to help reconcile and track down problems at an infrastructure level. For example, AWS API Gateway and AWS Lambda (used by Netlify, for example) provides requestId on the event.

You can include the request identifier setting the requestId logger option to true.

api/src/functions/graphql.ts
// ...
export const handler = createGraphQLHandler({
loggerConfig: { logger, options: { requestId: true } },
// ...

And then, when working to resolve a support issue with your deployment provider, you can supply this request id to help them track down and investigate the problem more easily.

No Need to Log within Services

By configuring your GraphQL logger to include data and query information about each request you can keep your service implementation clean, concise and free of repeated logger statements in every resolver -- and still log the useful debugging information.

api/src/functions/graphql.ts
// ...
export const handler = createGraphQLHandler({
loggerConfig: { logger, options: { data: true, operationName: true, query: true } },
// ...

// api/src/services/posts.js
//...
export const post = async ({ id }) => {
return await db.post.findUnique({
where: { id },
})
}
//...

The GraphQL handler will then take care of logging your query and data -- as long as your logger is setup to log at the info level and above.

You can also disable the statements in production by just logging at the warn level or above

This means that you can keep your services free of logger statements, but still see what's happening!

api | POST /graphql 200 7.754 ms - 1772
api | DEBUG [2021-09-29 16:04:09.313 +0000] (graphql-server): GraphQL execution started: BlogPostQuery
api | operationName: "BlogPostQuery"
api | query: {
api | "id": 3
api | }
api | DEBUG [2021-09-29 16:04:09.321 +0000] (graphql-server): GraphQL execution completed: BlogPostQuery
api | data: {
api | "post": {
api | "id": 3,
api | "body": "Meh waistcoat succulents umami asymmetrical, hoodie post-ironic paleo chillwave tote bag. Trust fund kitsch waistcoat vape, cray offal gochujang food truck cloud bread enamel pin forage. Roof party chambray ugh occupy fam stumptown. Dreamcatcher tousled snackwave, typewriter lyft unicorn pabst portland blue bottle locavore squid PBR&B tattooed.",
api | "createdAt": "2021-09-24T16:51:06.198Z",
api | "__typename": "Post"
api | }
api | }
api | operationName: "BlogPostQuery"
api | query: {
api | "id": 3
api | }
api | POST /graphql 200 9.386 ms - 441

Send to Third-party Transports

Stream to third-party log and application monitoring services vital to production logging in serverless environments like logFlare, Datadog or LogDNA

Supports Log Redaction

Everyone has heard of reports that Company X logged emails, or passwords to files or systems that may not have been secured. While RedwoodJS logging won't necessarily prevent that, it does provide you with the mechanism to ensure that won't happen.

To redact sensitive information, you can supply paths to keys that hold sensitive data using the RedwoodJS logger redact option.

Because this logger is used with the GraphQL handler, it will respect any redaction paths setup.

For example, you have chosen to log data return by each request, then you may want to redact sensitive information, like email addresses from your logs.

Here is an example of an application /api/src/lib/logger.ts configured to redact email addresses. Take note of the path data.users[*].email as this says, in the data attribute, redact the email from every user:

/api/src/lib/logger.ts
import { createLogger, redactionsList } from '@redwoodjs/api/logger'

export const logger = createLogger({
options: {
redact: [...redactionsList, 'email', 'data.users[*].email'],
},
})

Timing Traces and Metrics

Often you want to measure and report how long your queries take to execute and respond. You may already be measuring these durations at the database level, but you can also measure the time it takes for your the GraphQL server to parse, validate, and execute the request.

You may turn on logging these metrics via the tracing GraphQL configuration option.

api/src/functions/graphql.ts
// ...
export const handler = createGraphQLHandler({
loggerConfig: { logger, options: { tracing: true } },
// ...

Let's say we wanted to get some benchmark numbers for the "find post by id" resolver

return await db.post.findUnique({
where: { id },
})

We see that this request took about 500 msecs (note: duration is reported in nanoseconds).

For more details about the information logged and its format, see Apollo Tracing.

pi | INFO [2021-07-09 14:25:52.452 +0000] (graphql-server): GraphQL willSendResponse
api | tracing: {
api | "version": 1,
api | "startTime": "2021-07-09T14:25:51.931Z",
api | "endTime": "2021-07-09T14:25:52.452Z",
api | "duration": 521131526,
api | "execution": {
api | "resolvers": [
api | {
api | "path": [
api | "post"
api | ],
api | "parentType": "Query",
api | "fieldName": "post",
api | "returnType": "Post!",
api | "startOffset": 1787428,
api | "duration": 519121497
api | },
api | {
api | "path": [
api | "post",
api | "id"
api | ],
api | "parentType": "Post",
api | "fieldName": "id",
api | "returnType": "Int!",
api | "startOffset": 520982888,
api | "duration": 25140
api | },
... more paths follow ...
api | ]
api | }
api | }

By logging the operation name and extracting the duration for each query, you can easily collect and benchmark query performance.

Security

We'll document more GraphQL security best practices as Redwood reaches a v1.0 release candidate. For now, know that Redwood already has some baked-in best practices; for example, when deploying GraphQL to production, GraphQL Playground is automatically disabled.

Secure Services

Some of the biggest security improvements we'll be making revolve around Services (which are intimately linked to GraphQL since they're wrapped into your resolvers). For v1.0 we plan to make all of your GraphQL resolvers secure by default. You can even opt into this behavior now—see the Secure Services section.

Introspection and Playground Disabled in Production

Because it is often useful to ask a GraphQL schema for information about what queries it supports, GraphQL allows us to do so using the introspection system.

The GraphQL Playground is a way for you to interact with your schema and try out queries and mutations. It can show you the schema by inspecting it. You can find the GraphQL Playground at http://localhost:8911/graphql when your dev server is running.

Because both introspection and the playground share possibly sensitive information about your data model, your data, your queries and mutations, best practices for deploying a GraphQL Server call to disable these in production, RedwoodJS only enables introspection and the playground when running in development. That is when process.env.NODE_ENV === 'development'.

Query Depth Limit

Attackers often submit expensive, nested queries to abuse query depth that could overload your database or expend costly resources.

Typically, these types of unbounded, complex and expensive GraphQL queries are usually huge deeply nested and take advantage of an understanding of your schema (hence why schema introspection is disabled by default in production) and the data model relationships to create "cyclical" queries.

An example of a cyclical query here takes advantage of knowing that and author has posts and each post has and author ... that has posts ... that has an another that ... etc.

This cyclical query has a depth of 8.

// cyclical query example
// depth: 8+
query cyclical {
author(id: 'jules-verne') {
posts {
author {
posts {
author {
posts {
author {
... {
... # more deep nesting!
}
}
}
}
}
}
}
}
}

To mitigate the risk of attacking your application via deeply nested queries, RedwoodJS by default sets the Query Depth Limit to 11.

You can change the default value via the depthLimitOptions setting when creating your GraphQL handler.

You depthLimitOptions are maxDepth or ignore stops recursive depth checking based on a field name. Ignore can be either a string or regexp to match the name, or a function that returns a boolean.

For example:

// ...
export const handler = createGraphQLHandler({
loggerConfig: { logger, options: { query: true } },
depthLimitOptions: { maxDepth: 6 },
// ...
})

Error Masking

In many GraphQL servers, when an error is thrown, the details of that error are leaked to the outside world. The error and its message are then returned in the response and a client might reveal those errors in logs or even render the message to the user. You could potentially leak sensitive or other information about your app you don't want to share—such as database connection failures or even the presence of certain fields.

Redwood is here to help!

Redwood prevents leaking sensitive error-stack information out-of-the-box for unexpected errors. If an error that isn't one of Redwood's GraphQL Errors or isn't based on a GraphQLError is thrown:

  • The original error and its message will be logged using the defined GraphQL logger, so you'll know what went wrong
  • A default message "Something went wrong" will replace the error message in the response (Note: you can customize this message)

Customizing the Error Message

But what if you still want to share an error message with client? Simply use one of Redwood's GraphQL Errors and your custom message will be shared with your users.

Customizing the Default Error Message

You can customize the default "Something went wrong" message used when the error is masked via the defaultError setting on the createGraphQLHandler:

export const handler = createGraphQLHandler({
loggerConfig: { logger, options: {} },
directives,
sdls,
services,
defaultError: 'Sorry about that', // 👈 Customize the error message
onException: () => {
// Disconnect from your database with an unhandled exception.
db.$disconnect()
},
})

Redwood Errors

Redwood Errors are inspired from Apollo Server Error codes for common use cases:

To use a Redwood Error, import each from @redwoodjs/graphql-server.

  • SyntaxError - An unspecified error occurred
  • ValidationError - Invalid input to a service
  • AuthenticationError - Failed to authenticate
  • ForbiddenError - Unauthorized to access
  • UserInputError - Missing input to a service

If you use one of the errors, then the message provided will not be masked and will be shared in the GraphQL response:

import { UserInputError } from '@redwoodjs/graphql-server'
// ...
throw new UserInputError('An email is required.')

then the message provided will not be masked and it will be shred in the GraphQL response.

Custom Errors and Uses

Need you own custom error and message?

Maybe you're integrating with a third-party api and want to handle errors from that service and also want control of how that error is shared with your user client-side.

Simply extend from RedwoodGraphQLError and you're all set!

export class MyCustomError extends RedwoodGraphQLError {
constructor(message: string, extensions?: Record<string, any>) {
super(message, extensions)
}
}

For example, in your service, you can create and use it to handle the error and return a friendly message:

export class WeatherError extends RedwoodGraphQLError {
constructor(message: string, extensions?: Record<string, any>) {
super(message, extensions)
}
}

export const getWeather = async ({ input }: WeatherInput) {
try {
const weather = weatherClient.get(input.zipCode)
} catch(error) {
// rate limit issue
if (error.statusCode = 429) {
throw new WeatherError('Unable to get the latest weather updates at the moment. Please try again shortly.')
}

// other error
throw new WeatherError(`We could not get the weather for ${input.zipCode}.`)
}
}

FAQ

Why Doesn't Redwood Use Something Like Nexus?

This might be one of our most frequently asked questions of all time. Here's Tom's response in the forum:

We started with Nexus, but ended up pulling it out because we felt like it was too much of an abstraction over the SDL. It’s so nice being able to just read the raw SDL to see what the GraphQL API is.