Setup Nextjs , Apollo client and Chakra UI for your upcomming projects
Tags: react, apolloclient, chakraui, nextjs
Published: 2021-06-09 03:42:50

I am now working on creating DEV Community blog project clone for learning purpose using MERNG (Graphql) . I have already written 6 part series for server and when i will proceed next on server i will come with next part. I was also started frontend in nextjs and apollo client with component design in chakra ui.

In this blog post i will share you how we can setup complete nextjs project using apollo and chakra for SSR.

### Initialize Nextjs project

```
yarn create next-app

```
> provide your project_name and do not forget to change directory to project dir
`cd project_name`


### Install required dependencies


```
yarn add @apollo/client graphql @chakra-ui/react @emotion/react @emotion/styled framer-motion 

```

> create a `src`  directory and move your `pages` inside `src`

`src/pages/_app.js`


```javascript

import { ChakraProvider, useTheme } from "@chakra-ui/react";
import { ApolloProvider } from "@apollo/client";

import theme from "../theme";
import client from "../apollo-client";
import ClientOnly from "../components/ClientOnly";

function MyApp({ Component, pageProps }) {
  return (
    <ChakraProvider theme={theme}>
      <ApolloProvider client={client}>
        <ClientOnly>
             
                <Component {...pageProps} />
       
        </ClientOnly>
      </ApolloProvider>
    </ChakraProvider>
  );
}

export default MyApp;


```


`src/pages/_document.js`

```javascript


import { ColorModeScript } from "@chakra-ui/react";
import NextDocument, { Html, Head, Main, NextScript } from "next/document";
import theme from "../theme";
export default class Document extends NextDocument {
  render() {
    return (
      <Html lang="en">
        <Head />
        <body>
          <ColorModeScript initialColorMode={theme.config.initialColorMode} />
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}




```

`src/theme.js`


```javascript

import { extendTheme } from "@chakra-ui/react";

const config = {
  initialColorMode: "dark",
  useSystemColorMode: true,
};

const theme = extendTheme({ config });
export default theme;



```



`src/apollo-client.js`


```javascript


import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";

const httpLink = createHttpLink({
  uri: "http://localhost:4000/graphql",
});

const authLink = setContext((_, { headers }) => {
  const token =
    typeof window !== "undefined" ? localStorage.getItem("token") : "";

  return {
    headers: {
      ...headers,
      authorization: token ? token : "",
    },
  };
});

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

export default client;


```


`src/components/CLientOnly.js`


```javascript

import { useEffect, useState } from "react";

export default function ClientOnly({ children, ...delegated }) {
  const [hasMounted, setHasMounted] = useState(false);

  useEffect(() => {
    setHasMounted(true);
  }, []);

  if (!hasMounted) {
    return null;
  }

  return <div {...delegated}>{children}</div>;
}


```


`src/pages/index.js`

```javascript


import React, { Fragment } from "react";
import client from "../../apollo-client";
import { gql } from "@apollo/client";
import {
  Box,
 
} from "@chakra-ui/react";

function Home({data}) {
 
  
  return (
    <Box>
       <pre>
          {JSON.stringify(data,null,4)}
      </pre>
    </Box>
  );
}

const GET_QUERY = gql`
  query Data($var: String!) {
    data(var: $var) {
    id
    title

    }
  }
`;


export async function getServerSideProps({query}) {
  try {
    const var = query.var;
    const { data } = await client.query({
      query: GET_DATA,
      variables: {
        var,
      },
    });

   

    return {
      props: {
        data:data.data
      
      },
    };
  } catch (error) {
    console.log(error);
  }
}

export default Home;

```