Z
Z
zhivulinal2020-06-24 16:56:32
JavaScript
zhivulinal, 2020-06-24 16:56:32

React + Apollo + Websocket. The header with the token in WS is not updated. How to treat?

I collect the front on the websocket.
I pass headers with tokens, if at the first load, then everything is fine.
If you reload the page, the token is also valid.
If POST, GET everything goes away too.
Doesn't work, the old value of the token if you update it without reloading.
How to treat? What am I doing wrong?

The code is like this:

const wsLink = new WebSocketLink({
    uri: `ws://localhost:3000/api`,
    options: {
        reconnect: true,
        connectionParams: {
            Authorization: `Bearer ${token}`,
        },
    }
});

const httpLink = createHttpLink({
    uri: 'http://localhost:3000/api',
    credentials: 'same-origin',
})

const link = split(
    ({ query }) => {
        const { kind, operation } = getMainDefinition(query);
        return kind === 'OperationDefinition' && operation === 'subscription';
    },

    wsLink,
    httpLink,
);

const authMiddleware = new ApolloLink((operation, forward) => {
    operation.setContext(({ headers = {} }) => ({
        headers: {
            ...headers,
            Authorization: `Bearer ${token}`,
        }
    }));

    return forward(operation);
})

const client = new ApolloClient({
    link: authMiddleware.concat(link),
    cache: new InMemoryCache(),
});

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question