0
0
GraphQLquery~30 mins

Context setup in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
GraphQL Context Setup for User Authentication
📋 What You'll Learn
💡 Why This Matters
🌍 Real World
GraphQL context is used in real applications to pass authentication and other request-specific data to resolvers, enabling personalized and secure data access.
💼 Career
Understanding GraphQL context setup is essential for backend developers working with GraphQL APIs, especially in roles involving user authentication and authorization.
Progress0 / 4 steps
1
Define the GraphQL schema with a currentUser query
Create a GraphQL schema string called typeDefs that defines a Query type with a currentUser field returning a User type. Also define the User type with a name field of type String.
GraphQL
Hint

Define type User with a name field, and type Query with currentUser: User.

2
Create a context function that adds a user object
Create a function called context that takes a { req } parameter and returns an object with a user property set to { name: 'Alice' } to simulate an authenticated user.
GraphQL
Hint

Return an object with user set to { name: 'Alice' } inside the context function.

3
Write resolver for currentUser using context
Create a resolvers object with a Query field. Inside Query, write a currentUser resolver function that takes parent, args, and context parameters and returns context.user.
GraphQL
Hint

Return context.user from the currentUser resolver function.

4
Complete server setup with schema, resolvers, and context
Create an ApolloServer instance called server using typeDefs, resolvers, and context. Use new ApolloServer({ typeDefs, resolvers, context }).
GraphQL
Hint

Pass typeDefs, resolvers, and context to the ApolloServer constructor.