⬡ GraphQL Beginner

How do you authenticate in GraphQL?

Answer

GraphQL doesn't have built-in authentication — it delegates to the application layer. Common patterns: (1) HTTP headers: send a JWT in the Authorization: Bearer TOKEN header with every request. The GraphQL server extracts and verifies the token in the context function, making the user object available to all resolvers. (2) Session cookies: work the same as with REST APIs — the browser sends cookies automatically. (3) OAuth/OIDC: implement standard OAuth flows with redirect; the resulting access token is used in Authorization header. In resolvers, check context.user: if (!context.user) throw new GraphQLError('Unauthenticated', { extensions: { code: 'UNAUTHENTICATED' } });. Never put authentication logic in individual resolvers repeatedly — use schema directives (@auth) or middleware for DRY authentication.