Introduction
Authentication errors tell us when someone tries to access data without permission. They help keep data safe.
Authentication errors tell us when someone tries to access data without permission. They help keep data safe.
type Query {
secureData: String
}
const resolvers = {
Query: {
secureData(parent, args, context) {
if (!context.user) {
throw new AuthenticationError('You must be logged in');
}
return 'Secret info';
}
}
};if (!context.user) { throw new AuthenticationError('Not logged in'); }
if (!context.user.isAdmin) { throw new AuthenticationError('Admin access required'); }
This GraphQL server checks if the user is logged in by looking for a valid token in the request headers. If the token is missing or invalid, it throws an authentication error when trying to get the secret message.
const { ApolloServer, gql, AuthenticationError } = require('apollo-server'); const typeDefs = gql` type Query { secretMessage: String } `; const resolvers = { Query: { secretMessage(parent, args, context) { if (!context.user) { throw new AuthenticationError('You must be logged in to see this message'); } return 'This is a secret message'; } } }; const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { // Simulate user authentication const token = req.headers.authorization || ''; if (token === 'valid-token') { return { user: { id: 1, name: 'Alice' } }; } return {}; } }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
Always check authentication early in your resolver to avoid exposing data.
Use clear error messages so users know why access was denied.
Authentication errors protect data by stopping unauthorized access.
They are thrown inside resolvers using the context user info.
Check user info in context before returning sensitive data.
function resolver(parent, args, context) {
if (!context.user) {
throw new Error('Not authenticated');
}
return 'Secret Data';
}context.user is null?function resolver(parent, args, context) {
if (context.user === undefined) {
throw new Error('Not authenticated');
}
return 'User data';
}function getUserProfile(parent, args, context) {
// Your code here
}Pass the test and this pattern moves unknown