Security News
Supply Chain Attack Detected in Solana's web3.js Library
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
apollo-link-http
Advanced tools
The apollo-link-http package is used to connect Apollo Client to a GraphQL server over HTTP. It provides a standard way to send GraphQL queries and mutations to a server, handle responses, and manage errors.
Basic HTTP Link
This code demonstrates how to create a basic HTTP link to connect to a GraphQL server using the apollo-link-http package. The `createHttpLink` function is used to specify the URI of the GraphQL server, and the link is then used to configure the Apollo Client.
const { createHttpLink } = require('apollo-link-http');
const { ApolloClient, InMemoryCache } = require('@apollo/client');
const httpLink = createHttpLink({
uri: 'https://example.com/graphql',
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
});
Setting HTTP Headers
This code demonstrates how to set HTTP headers, such as an authorization token, for each request. The `setContext` function from `apollo-link-context` is used to modify the headers before the request is sent.
const { createHttpLink } = require('apollo-link-http');
const { ApolloClient, InMemoryCache } = require('@apollo/client');
const { setContext } = require('apollo-link-context');
const httpLink = createHttpLink({
uri: 'https://example.com/graphql',
});
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: localStorage.getItem('token') || '',
}
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
Error Handling
This code demonstrates how to handle errors in GraphQL requests. The `onError` function from `apollo-link-error` is used to log GraphQL and network errors.
const { createHttpLink } = require('apollo-link-http');
const { ApolloClient, InMemoryCache } = require('@apollo/client');
const { onError } = require('apollo-link-error');
const httpLink = createHttpLink({
uri: 'https://example.com/graphql',
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path }) => {
console.log(`GraphQL error: ${message}`);
});
}
if (networkError) {
console.log(`Network error: ${networkError}`);
}
});
const client = new ApolloClient({
link: errorLink.concat(httpLink),
cache: new InMemoryCache(),
});
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. It includes functionalities for connecting to a GraphQL server, caching, and error handling, similar to apollo-link-http, but with a broader scope.
Relay is a JavaScript framework for building data-driven React applications. It is similar to apollo-link-http in that it connects to a GraphQL server, but it also includes advanced features like data fetching, caching, and state management, optimized for performance.
urql is a highly customizable and versatile GraphQL client for React. It provides similar functionalities to apollo-link-http, such as connecting to a GraphQL server and handling queries and mutations, but it is designed to be more lightweight and modular.
The http link is the most common Apollo Link, a system of modular components for GraphQL networking. If you haven't done so already, read the Apollo Link docs to learn about the Apollo Link ecosystem and how to use this link with libraries like Apollo Client and graphql-tools, or as a standalone client.
The http link is a terminating link that fetches GraphQL results from a GraphQL endpoint over an http connection. The http link supports both POST and GET requests with the ability change the http options on a per query basis. This can be used for authentication, persisted queries, dynamic uris, and other granular updates.
Import and initialize this link in just two lines:
import { createHttpLink } from "apollo-link-http";
const link = createHttpLink({ uri: "/graphql" });
HTTP Link takes an object with some options on it to customize the behavior of the link. If your server supports it, the HTTP link can also send over metadata about the request in the extensions field. To enable this, pass includeExtensions
as true. The options you can pass are outlined below:
uri
: the URI key is a string endpoint or function resolving to an endpoint -- will default to "/graphql" if not specifiedincludeExtensions
: allow passing the extensions field to your graphql server, defaults to falsefetch
: a fetch
compatible API for making a requestheaders
: an object representing values to be sent as headers on the requestcredentials
: a string representing the credentials policy you want for the fetch callfetchOptions
: any overrides of the fetch options argument to pass to the fetch calluseGETForQueries
: set to true
to use the HTTP GET
method for queries (but not for mutations)The HTTP Link relies on having fetch
present in your runtime environment. If you are running on react-native, or modern browsers, this should be no problem. If you are targeting an environment without fetch
such as older browsers or the server, you will need to pass your own fetch
to the link through the options. We recommend unfetch
for older browsers and node-fetch
for running in Node.
The Http Link uses the headers
field on the context to allow passing headers to the HTTP request. It also supports the credentials
field for defining credentials policy, uri
for changing the endpoint dynamically, and fetchOptions
to allow generic fetch overrides (i.e. method: "GET"
). These options will override the same key if passed when creating the the link.
Note that if you set fetchOptions.method
to GET
, the http link will follow the standard GraphQL HTTP GET encoding: the query, variables, operation name, and extensions will be passed as query parameters rather than in the HTTP request body. If you want mutations to continue to be sent as non-idempotent POST
requests, set the top-level useGETForQueries
option to true
instead of setting fetchOptions.method
to GET
.
This link also attaches the response from the fetch
operation on the context as response
so you can access it from within another link.
headers
: an object representing values to be sent as headers on the requestcredentials
: a string representing the credentials policy you want for the fetch calluri
: a string of the endpoint you want to fetch fromfetchOptions
: any overrides of the fetch options argument to pass to the fetch callresponse
: this is the raw response from the fetch request after it is made.http
: this is an object to control fine grained aspects of the http link itself, such as persisted queries (see below)The http link supports an advanced GraphQL feature called persisted queries. This allows you to not send the stringified query over the wire, but instead send some kind of identifier of the query. To support this you need to attach the id somewhere to the extensions field and pass the following options to the context:
operation.setContext({
http: {
includeExtensions: true,
includeQuery: false,
}
})
The http
object on context currently supports two keys:
includeExtensions
: Send the extensions object for this request.includeQuery
: Don't send the query
field for this request.One way to use persisted queries is with apollo-link-persisted-queries and Apollo Engine.
Apollo Client supports passing context separately for every query, so you can do things like pass a special header for a single query invocation if you need to.
import HttpLink from "apollo-link-http";
import ApolloClient from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
const client = new ApolloClient({
link: new HttpLink({ uri: "/graphql" }),
cache: new InMemoryCache()
});
// a query with apollo-client
client.query({
query: MY_QUERY,
context: {
// example of setting the headers with context per operation
headers: {
special: "Special header value"
}
}
});
The Http Link draws a distinction between client, server and GraphQL errors. Server errors can occur in three different scenarios: parse, network and data errors. apollo-link-error
provides an interface for handling these errors. This list describes the scenarios that cause different errors:
data
or errors
errors
array for a 200 level statusSince many server implementations can return a valid GraphQL result on a server network error, the thrown Error
object contains the parsed server result. A server data error also receives the parsed result.
The table below provides a summary of error, Observable
method called by the HTTP link, and type of error thrown for each failure:
Error | Callback | Error Type |
---|---|---|
Client Parse | error | ClientParseError |
Server Parse | error | ServerParseError |
Server Network | error | ServerError |
Server Data | error | ServerError |
GraphQL Error | next | Object |
All error types inherit the name
, message
, and nullable stack
properties from the generic javascript Error.
//type ClientParseError
{
parseError: Error; // Error returned from response.json()
};
//type ServerParseError
{
response: Response; // Object returned from fetch()
statusCode: number; // HTTP status code
bodyText: string // text that was returned from server
};
//type ServerError
{
result: Record<string, any>; // Parsed object from server response
response: Response; // Object returned from fetch()
statusCode: number; // HTTP status code
};
You can use the fetch
option when creating an http-link to do a lot of custom networking. This is useful if you want to modify the request based on the calculated headers or calculate the uri based on the operation:
const customFetch = (uri, options) => {
const { header } = Hawk.client.header(
"http://example.com:8000/resource/1?b=1&a=2",
"POST",
{ credentials: credentials, ext: "some-app-data" }
);
options.headers.Authorization = header;
return fetch(uri, options);
};
const link = createHttpLink({ fetch: customFetch });
const customFetch = (uri, options) => {
const { operationName } = JSON.parse(options.body);
return fetch(`${uri}/graph/graphql?opname=${operationName}`, options);
};
const link = createHttpLink({ fetch: customFetch });
If you previously used either apollo-fetch
or apollo-client
's createNetworkInterface
, you will need to change the way use
and useAfter
are implemented in your app. Both can be implemented by writing a custom link. It's important to note that regardless of whether you're adding middleware or afterware, your Http link will always be last in the chain since it's a terminating link.
Before
// before
import ApolloClient, { createNetworkInterface } from "apollo-client";
const networkInterface = createNetworkInterface({ uri: "/graphql" });
networkInterface.use([
{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {}; // Create the header object if needed.
}
req.options.headers["authorization"] = localStorage.getItem("token")
? localStorage.getItem("token")
: null;
next();
}
}
]);
After
import { ApolloLink } from "apollo-link";
import { createHttpLink } from "apollo-link-http";
const httpLink = createHttpLink({ uri: "/graphql" });
const middlewareLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
authorization: localStorage.getItem("token") || null
}
});
return forward(operation);
});
// use with apollo-client
const link = middlewareLink.concat(httpLink);
Before
import ApolloClient, { createNetworkInterface } from "apollo-client";
import { logout } from "./logout";
const networkInterface = createNetworkInterface({ uri: "/graphql" });
networkInterface.useAfter([
{
applyAfterware({ response }, next) {
if (response.statusCode === 401) {
logout();
}
next();
}
}
]);
After
import { ApolloLink } from "apollo-link";
import { createHttpLink } from "apollo-link-http";
import { onError } from "apollo-link-error";
import { logout } from "./logout";
const httpLink = createHttpLink({ uri: "/graphql" });
const errorLink = onError(({ networkError }) => {
if (networkError.status === 401) {
logout();
}
});
// use with apollo-client
const link = errorLink.concat(httpLink);
Before
import ApolloClient, { createNetworkInterface } from "apollo-client";
import { logout } from "./logout";
const networkInterface = createNetworkInterface({ uri: "/graphql" });
networkInterface.useAfter([
{
applyAfterware({ response }, next) {
if (response.data.user.lastLoginDate) {
response.data.user.lastLoginDate = new Date(
response.data.user.lastLoginDate
);
}
next();
}
}
]);
After
import { ApolloLink } from "apollo-link";
import { createHttpLink } from "apollo-link-http";
const httpLink = createHttpLink({ uri: "/graphql" });
const addDatesLink = new ApolloLink((operation, forward) => {
return forward(operation).map(response => {
if (response.data.user.lastLoginDate) {
response.data.user.lastLoginDate = new Date(
response.data.user.lastLoginDate
);
}
return response;
});
});
// use with apollo-client
const link = addDatesLink.concat(httpLink);
FAQs
HTTP transport layer for GraphQL
The npm package apollo-link-http receives a total of 423,410 weekly downloads. As such, apollo-link-http popularity was classified as popular.
We found that apollo-link-http demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.