Imagine you have a GraphQL API that needs to allow users to access data only if they are logged in and have the right permissions. What is the main role of context-based authentication in this scenario?
Think about how the server knows who is making the request and what they are allowed to see.
Context-based authentication in GraphQL means passing user info and permissions in the context object for each request. This helps resolvers decide if the user can access certain data.
Given this resolver snippet, what will be the output if the user is not authenticated?
const resolver = (parent, args, context) => { if (!context.user) { return 'Access denied'; } return 'Welcome ' + context.user.name; }; // context = {} (no user key)
Check what happens when context.user is missing.
The resolver checks if context.user exists. If not, it returns 'Access denied'. Since the context has no user, it returns that message.
Which option correctly fixes the syntax error in this GraphQL server context function?
const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { const token = req.headers.authorization; if (!token) { throw new Error('No token'); } const user = getUserFromToken(token); return { user }; } });
Check if the arrow function syntax and object return are valid.
The context function uses concise arrow function syntax returning an object. The code is syntactically correct.
You want to avoid decoding the user token multiple times in nested resolvers. Which approach optimizes context-based authentication?
Think about doing work once per request instead of multiple times.
Decoding the token once in the context function is efficient. It avoids repeated work and ensures consistent user info for all resolvers.
Consider this resolver code snippet:
const resolver = (parent, args, context) => {
if (context.user.role !== 'admin') {
throw new Error('Unauthorized');
}
return 'Secret data';
};
// context = {} (empty object)Why does this code cause an error?
Check what happens when you try to access a property of something that does not exist.
Accessing context.user.role when context.user is undefined causes a runtime error. The code should first check if context.user exists.