0
0
GraphQLquery~30 mins

Context-based authentication in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Context-based Authentication with GraphQL
📖 Scenario: You are building a simple GraphQL API for a small online store. The API needs to authenticate users based on a context token to allow access to user-specific data.
🎯 Goal: Build a GraphQL schema and resolver setup that uses context-based authentication to return user data only if the correct token is provided.
📋 What You'll Learn
Create a GraphQL schema with a User type and a Query type with a me field
Add a context object that contains a token string
Implement a resolver for me that checks the token in context and returns user data if the token matches
Return null if the token is missing or invalid
💡 Why This Matters
🌍 Real World
Context-based authentication is used in real APIs to control access to user data based on tokens or session info.
💼 Career
Understanding how to use context in GraphQL for authentication is essential for backend developers building secure APIs.
Progress0 / 4 steps
1
Define the GraphQL schema
Create a GraphQL schema string called typeDefs that defines a User type with fields id (ID!), name (String!), and a Query type with a me field returning User.
GraphQL
Hint

Define the schema as a template string with the required types and fields.

2
Add context with token
Create a variable called context that is an object with a token property set to the string "secret-token-123".
GraphQL
Hint

Create a simple object with the token string.

3
Implement the resolver with token check
Create a resolvers object with a Query field containing a me function. This function takes parent, args, and ctx parameters and returns an object { id: "1", name: "Alice" } only if ctx.token equals "secret-token-123". Otherwise, return null.
GraphQL
Hint

Use a simple if statement inside the resolver to check the token.

4
Complete the GraphQL server setup
Create a variable called server that is an instance of ApolloServer initialized with typeDefs, resolvers, and a context function returning the context object.
GraphQL
Hint

Use new ApolloServer with the correct options.