How to Pass Token in GraphQL Request: Simple Guide
To pass a token in a GraphQL request, include it in the HTTP headers, typically using the
Authorization header with a value like Bearer YOUR_TOKEN. This allows the server to authenticate the request securely.Syntax
When sending a GraphQL request, the token is usually passed in the HTTP headers. The common header used is Authorization. The value often starts with Bearer followed by a space and then the token string.
This looks like:
Authorization: The header key where the token is sent.Bearer YOUR_TOKEN: The value format whereYOUR_TOKENis your actual token.
http
Authorization: Bearer YOUR_TOKEN
Example
This example shows how to send a GraphQL query with a token using JavaScript's fetch API. The token is added in the Authorization header to authenticate the request.
javascript
const query = ` query GetUserData { user { id name } } `; const token = 'your_token_here'; fetch('https://example.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ query }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Output
{
"data": {
"user": {
"id": "123",
"name": "Alice"
}
}
}
Common Pitfalls
Common mistakes when passing tokens in GraphQL requests include:
- Not including the
Authorizationheader at all. - Forgetting the
Bearerprefix before the token. - Sending the token in the request body instead of headers.
- Using an expired or invalid token.
Always check your token format and header placement.
javascript
/* Wrong way: token in body (won't authenticate) */ fetch('https://example.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: '{ user { id name } }', token: 'your_token_here' }) }); /* Right way: token in Authorization header */ fetch('https://example.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_token_here' }, body: JSON.stringify({ query: '{ user { id name } }' }) });
Quick Reference
| Step | What to Do | Example |
|---|---|---|
| 1 | Add Authorization header | Authorization: Bearer YOUR_TOKEN |
| 2 | Set Content-Type header | Content-Type: application/json |
| 3 | Send GraphQL query in body | {"query": "{ user { id name } }"} |
| 4 | Use fetch or HTTP client | fetch(url, { headers, body }) |
Key Takeaways
Always pass the token in the HTTP Authorization header using the Bearer scheme.
Do not send tokens inside the GraphQL query or variables; use headers instead.
Ensure the token is valid and not expired to avoid authentication errors.
Set Content-Type to application/json when sending GraphQL requests.
Use your HTTP client’s header options to include the token securely.