{"id":352798,"date":"2021-10-01T07:35:02","date_gmt":"2021-10-01T14:35:02","guid":{"rendered":"https:\/\/css-tricks.com\/?p=352798"},"modified":"2021-10-01T07:35:05","modified_gmt":"2021-10-01T14:35:05","slug":"working-with-built-in-graphql-directives","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/working-with-built-in-graphql-directives\/","title":{"rendered":"Working With Built-in GraphQL Directives"},"content":{"rendered":"\n

Directives<\/strong> are one of GraphQL\u2019s best \u2014 and most unspoken \u2014 features.<\/p>\n\n\n\n

Let’s explore working with GraphQL\u2019s built-in schema and operation directives that all GraphQL spec compliant APIs must implement. They are extremely useful if you are working with a dynamic front-end because you have the control to reduce the response payload depending on what the user is interacting with.<\/p>\n\n\n\n\n\n\n

An overview of directives<\/h3>\n\n\n

Let\u2019s imagine an application where you have the option to customize the columns shown in a table. If you hide two or three columns then there\u2019s really no need to fetch the data for those cells. With GraphQL directives, though, we can choose to include or skip those fields.<\/p>\n\n\n\n

The GraphQL specification defines what directives are<\/a>, and the location of where they can be used. Specifically, directives can be used by consumer operations (such as a query), and by the underlying schema itself. Or, in simple terms, directives are either based on schema or operation. Schema directives<\/strong><\/dfn> are used when the schema is generated, and operation directives<\/strong><\/dfn> run when a query is executed.<\/p>\n\n\n\n

In short, directives can be used for the purposes of metadata, runtime hints, runtime parsing (like returning dates in a specific format), and extended descriptions (like deprecated).<\/p>\n\n\n

Four kinds of directives<\/h3>\n\n\n

GraphQL boasts four main directives as defined in the specification working draft<\/a>, with one of them unreleased as a working draft.<\/p>\n\n\n\n