npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nextjs-with-apollo

v1.0.1

Published

[![NPM Status][npm-image]][npm-url] [![GitHub license][license-image]][license-url] [![LGTM Status][lgtm-image]][lgtm-url] [![Codacy Badge](https://api.codacy.com/project/badge/Grade/7588b3bdb457430687e3688bf2cd6121)](https://www.codacy.com/manual/subash.

Downloads

52

Readme

NPM Status GitHub license LGTM Status Codacy Badge Dependencies

⚓ nextjs-with-apollo

Apollo HOC for NextJS.

Install

Install the package with npm

npm install nextjs-with-apollo

or with yarn

yarn add nextjs-with-apollo

Basic Usage

  1. Create a HOC

Create the HOC using a basic setup.

// hocs/withApollo.js
import withApollo from 'nextjs-with-apollo';
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';

const GRAPHQL_URL = 'https://your-graphql-url';

const createApolloClient = ({ initialState, headers }) =>
    new ApolloClient({
      uri: GRAPHQL_URL,
      cache: new InMemoryCache().restore(initialState || {}) // hydrate cache
    });
    
export default withApollo(createApolloClient);

Parameters initialState and headers are received in the hoc.

If the render is happening in server, all headers received by the server can be accessed via headers. If the render is happening in browser, we hydrate the client cache with the initial stated created in server.

  1. Now use the HOC
import React from 'react';
import { useQuery } from '@apollo/react-hooks';

import withApollo from 'hocs/withApollo';

const QUERY = gql`
  query Profile {
    profile {
      name
      displayname
    }
  }
`;

const ProfilePage = () => {
  const { loading, error, data } = useQuery(PROFILE_QUERY);

  if (loading) {
    return <p>loading..</p>;
  }

  if (error) {
    return JSON.stringify(error);
  }

  return (
    <>
      <p>user name: {data.profile.displayname}</p>
      <p>name: {data.profile.name}</p>
    </>
  );
};

export default withApollo(ProfilePage);

Thats all. Now Profile page will be rendered in the server. You do not need to do anything in getInitialProps. All queries are resolved in the sever.

If you dont want to SSR the above page then you can pass {ssr: false} to the hoc.

export default withApollo(ProfilePage, { ssr: false });

If you want, you can also access instance of apolloClient in getInitialProps.

ProfilePage.getInitialProps = ctx => {
  const apolloClient = ctx.apolloClient;
};

SSR with auth

Often graphQL server requires AuthorizationToken for authorizing requests. We can use the headers received in server to parse token from client side cookies.

// hocs/withApollo.js
import withApollo from 'nextjs-with-apollo';
import fetch from 'isomorphic-unfetch';
import { InMemoryCache } from 'apollo-cache-inmemory';
import ApolloClient from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { ApolloLink } from 'apollo-link';
import { setContext } from 'apollo-link-context';
import cookie from 'cookie';
import get from 'lodash/get';

const isServer = typeof window === 'undefined';

const getToken = headers => {
  const COOKIE_NAME = 'your_auth_cookie_name'
  const cookies = isServer ? get(headers, 'cookie', '') : document.cookie;

  return get(cookie.parse(cookies), COOKIE_NAME, '');
};

const attachAuth = headers => () => {
  const token = getToken(headers);

  return {
    headers: {
      authorization: `Bearer ${token}`
    }
  };
};

const createApolloClient = ({ initialState, headers = {} }) => {
  const authLink = () => setContext(attachAuth(headers));

  const httpLink = new HttpLink({
    credentials: 'include',
    uri: GRAPHQL_ENDPOINT,
    fetch
  });

  return new ApolloClient({
    ssrMode: isServer,
    link: ApolloLink.from([authLink(), httpLink]),
    cache: new InMemoryCache().restore(initialState || {})
  });
};

export default withApollo(createApolloClient);

License

Feel free to use the code, it's released using the MIT license.