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.
GraphQL 101
GraphQL is a query language that enhances the exchange of data between clients (in Redwood's case, a React app) and servers (a Redwood API).
Unlike a REST API, a GraphQL Client performs operations that allow gathering a rich dataset in a single request. There's three types of GraphQL operations, but here we'll only focus on two: Queries (to read data) and Mutations (to create, update, or delete data).
The following GraphQL query:
query GetProject {
project(name: "GraphQL") {
id
title
description
owner {
id
username
}
tags {
id
name
}
}
}
returns the following JSON response:
{
"data": {
"project": {
"id": 1,
"title": "My Project",
"description": "Lorem ipsum...",
"owner": {
"id": 11,
"username": "Redwood",
},
"tags": [
{ "id": 22, "name": "graphql" }
]
}
},
"errors": null
}
Notice that the response's structure mirrors the query's. In this way, GraphQL makes fetching data descriptive and predictable.
Again, unlike a REST API, a GraphQL API is built on a schema that specifies exactly which queries and mutations can be performed.
For the GetProject
query above, here's the schema backing it:
type Project {
id: ID!
title: String
description: String
owner: User!
tags: [Tag]
}
# ... User and Tag type definitions
type Query {
project(name: String!): Project
}
More information on GraphQL types can be found in the official GraphQL documentation.
Finally, the GraphQL schema is associated with a resolvers map that helps resolve each requested field. For example, here's what the resolver for the owner field on the Project type may look like:
export const Project = {
owner: (args, { root, context, info }) => {
return db.project.findUnique({ where: { id: root.id } }).user()
},
// ...
}
You can read more about resolvers in the dedicated Understanding Default Resolvers section below.
To summarize, when a GraphQL query reaches a GraphQL API, here's what happens:
+--------------------+ +--------------------+
| | 1.send operation | |
| | | GraphQL Server |
| GraphQL Client +----------------->| | |
| | | | 2.resolve |
| | | | data |
+--------------------+ | v |
^ | +----------------+ |
| | | | |
| | | Resolvers | |
| | | | |
| | +--------+-------+ |
| 3. respond JSON with data | | |
+-----------------------------+ <--------+ |
| |
+--------------------+
In contrast to most GraphQL implementations, Redwood provides a "deconstructed" way of creating a GraphQL API:
- You define your SDLs (schema) in
*.sdl.js
files, which define what queries and mutations are available, and what fields can be returned - For each query or mutation, you write a service function with the same name. This is the resolver
- Redwood then takes all your SDLs and Services (resolvers), combines them into a GraphQL server, and expose it as an endpoint
RedwoodJS and GraphQL
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. 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.”
GraphQL Yoga and the Generic Computation 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 from The Guild makes that possible.
The fully-featured GraphQL Server with focus on easy setup, performance and great developer experience.
RedwoodJS leverages Yoga's Envelop plugins to implement custom internal plugins to help with authentication, logging, directive handling, and more.
Security Best Practices
RedwoodJS implements GraphQL Armor from Escape Technologies to make your endpoint more secure by default by implementing common GraphQL security best practices.
GraphQL Armor, developed by Escape in partnership with The Guild, is a middleware for JS servers that adds a security layer to the RedwoodJS GraphQL endpoint.
Conclusion
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:
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:
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:
Hook | Description |
---|---|
useLazyQuery | Execute queries in response to events other than component rendering |
useApolloClient | Access 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 root
—see 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:
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:
import { db } from 'src/lib/db'
export const users = () => {
return db.user.findMany()
}
Which begs the question: where are the resolvers for the User fields—id
, 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:
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 argumentobj
is namedroot
(all the rest keep their names)root
,context
, andinfo
are wrapped into an object,gqlArgs
; this object is passed as the second argument
Here's an example to make things clear:
export const Post = {
user: (args, gqlArgs) => db.post.findUnique({ where: { id: gqlArgs?.root.id } }).user(),
}
Of the four, you'll see args
and root
being used a lot.
Argument | Description |
---|---|
args | The arguments provided to the field in the GraphQL query |
root | The previous return in the resolver chain |
context | Holds important contextual information, like the currently logged in user |
info | Holds 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 itroot
, GraphQL Yoga calls itparent
.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:
// ...
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, theevent
information is available as an attribute of the context ascontext.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 running—yarn 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:
scalar BigInt
scalar Date
scalar Time
scalar DateTime
scalar JSON
scalar JSONObject
type Redwood {
version: String
currentUser: JSON
prismaVersion: String
}
type Query {
redwood: Redwood
}
Now that you've seen the sdl, be sure to check out the resolvers:
export const resolvers: Resolvers = {
BigInt: BigIntResolver,
Date: DateResolver,
Time: TimeResolver,
DateTime: DateTimeResolver,
JSON: JSONResolver,
JSONObject: JSONObjectResolver,
Query: {
redwood: () => ({
version: redwoodVersion,
prismaVersion: prismaVersion,
currentUser: (_args: any, context: GlobalContext) => {
return context?.currentUser
},
}),
},
}
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
You can use health checks to determine if a server is available and ready to start serving traffic. For example, services like Pingdom use health checks to determine server uptime and will notify you if it becomes unavailable.
Redwood's GraphQL server provides a health check endpoint at /graphql/health
as part of its GraphQL handler.
If the server is healthy and can accept requests, the response will contain the following headers:
content-type: application/json
server: GraphQL Yoga
x-yoga-id: yoga
and will return a HTTP/1.1 200 OK
status with the body:
{
"message": "alive"
}
Note the x-yoga-id
header. The header's value defaults to yoga
when healthCheckId
isn't set in createGraphQLHandler
. But you can customize it when configuring your GraphQL handler:
// ...
export const handler = createGraphQLHandler({
// This will be the value of the `x-yoga-id` header
healthCheckId: 'my-redwood-graphql-server',
getCurrentUser,
loggerConfig: { logger, options: {} },
directives,
sdls,
services,
onException: () => {
// Disconnect from your database with an unhandled exception.
db.$disconnect()
},
})
If the health check fails, then the GraphQL server is unavailable and you should investigate what could be causing the downtime.
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" -i
or by directly invoking the graphql function:
curl "http://localhost:8911/graphql/health" -i
you should get the response:
{
"message": "alive"
}
For production, make a request wherever your /graphql
function exists.
These examples use
curl
but you can perform a health check via any HTTP GET request.
Perform a Readiness Check
A readiness check confirms that your GraphQL server can accept requests and serve your server's traffic.
It forwards a request to the health check with a header that must match your healthCheckId
in order to succeed.
If the healthCheckId
doesn't match or the request fails, then your GraphQL server isn't "ready".
To perform a readiness check, make a HTTP GET request to the /graphql/readiness
endpoint with the appropriate healthCheckId
header.
For local development, you can make a request to the proxy:
curl "http://localhost:8910/.redwood/functions/graphql/readiness" \
-H 'x-yoga-id: yoga' \
-i
or directly invoke the graphql function:
curl "http://localhost:8911/graphql/readiness" \
-H 'x-yoga-id: yoga' \
-i
Either way, you should get a 200 OK
HTTP status if ready, or a 503 Service Unavailable
if not.
For production, make a request wherever your /graphql
function exists.
These examples use
curl
but you can perform a readiness check via any HTTP GET request with the proper headers.
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:
- 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.
export const schema = gql`
scalar Currency
`
- Import the scalar's definition and resolver and pass them to your GraphQLHandler via the
schemaOptions
property:
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()
},
})
- 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 {
products: [Product!]! @requireAuth
product(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's GraphQLHandlerOptions
allows you to configure your GraphQL handler schema, context, authentication, security and more.
export interface GraphQLHandlerOptions {
/**
* @description The identifier used in the GraphQL health check response.
* It verifies readiness when sent as a header in the readiness check request.
*
* By default, the identifier is `yoga` as seen in the HTTP response header `x-yoga-id: yoga`
*/
healthCheckId?: string
/**
* @description Customize GraphQL Logger
*
* Collect resolver timings, and exposes trace data for
* an individual request under extensions as part of the GraphQL response.
*/
loggerConfig: LoggerConfig
/**
* @description Modify the resolver and global context.
*/
context?: Context | ContextFunction
/**
* @description An async function that maps the auth token retrieved from the
* request headers to an object.
* Is it executed when the `auth-provider` contains one of the supported
* providers.
*/
getCurrentUser?: GetCurrentUser
/**
* @description A callback when an unhandled exception occurs. Use this to disconnect your prisma instance.
*/
onException?: () => void
/**
* @description Services passed from the glob import:
* import services from 'src/services\/**\/*.{js,ts}'
*/
services: ServicesGlobImports
/**
* @description SDLs (schema definitions) passed from the glob import:
* import sdls from 'src/graphql\/**\/*.{js,ts}'
*/
sdls: SdlGlobImports
/**
* @description Directives passed from the glob import:
* import directives from 'src/directives/**\/*.{js,ts}'
*/
directives?: DirectiveGlobImports
/**
* @description A list of options passed to [makeExecutableSchema]
* (https://www.graphql-tools.com/docs/generate-schema/#makeexecutableschemaoptions).
*/
schemaOptions?: Partial<IExecutableSchemaDefinition>
/**
* @description CORS configuration
*/
cors?: CorsConfig
/**
* @description Customize GraphQL Armor plugin configuration
*
* @see https://escape-technologies.github.io/graphql-armor/docs/configuration/examples
*/
armorConfig?: ArmorConfig
/**
* @description Customize the default error message used to mask errors.
*
* By default, the masked error message is "Something went wrong"
*
* @see https://github.com/dotansimha/envelop/blob/main/packages/core/docs/use-masked-errors.md
*/
defaultError?: string
/**
* @description Only allows the specified operation types (e.g. subscription, query or mutation).
*
* By default, only allow query and mutation (ie, do not allow subscriptions).
*
* An array of GraphQL's OperationTypeNode enums:
* - OperationTypeNode.SUBSCRIPTION
* - OperationTypeNode.QUERY
* - OperationTypeNode.MUTATION
*
* @see https://github.com/dotansimha/envelop/tree/main/packages/plugins/filter-operation-type
*/
allowedOperations?: AllowedOperations
/**
* @description Custom Envelop plugins
*/
extraPlugins?: Plugin[]
/**
* @description Auth-provider specific token decoder
*/
authDecoder?: Decoder
/**
* @description Customize the GraphiQL Endpoint that appears in the location bar of the GraphQL Playground
*
* Defaults to '/graphql' as this value must match the name of the `graphql` function on the api-side.
*/
graphiQLEndpoint?: string
/**
* @description Function that returns custom headers (as string) for GraphiQL.
*
* Headers must set auth-provider, Authorization and (if using dbAuth) the encrypted cookie.
*/
generateGraphiQLHeader?: GenerateGraphiQLHeader
}
Directive 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.
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: {} },
armorConfig, // 👈 custom GraphQL Security configuration
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 Setup
For a details on setting up GraphQL Logging, see Logging.