Full stack example using React, urql and GraphQL API - Part 1
Tags: graphql, react, urql, agoston
Published: 2022-10-20 06:50:13

Want a real-time full-stack application online in less than a day? This post describes the steps that let any (juniors, frontend) developers spawn their backend (with Agoston.io), set the minimum configuration, and start implementing authentication, GraphQL requests, and subscription.

## 1. Spawn your backend

Create an account on [Agoston.io](https://agoston.io). On the main page, create a new (free) backend:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74so7i4pm9e4vdp7v15t.png)

After a few minutes, you have a complete and secure backend with Postgres, Postgraphile, etc.

## 2. Enable Google Authentication

Click on the backend name. That will lead you to the backend configuration page. On the bottom part, you will find the authentication configuration.

Enable the Google authentication and input your `Client ID` and `Client secret` (you can get one following the Google instructions [here](https://developers.google.com/identity/protocols/oauth2)).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m45m09vfnklticlk0bzz.png)

**Callback URL:** Google will ask you for the callback URL. You will find it in the configuration page, section `Authentication strategies`, field `Callback URL`.

## 3. Reload the backend

Necessary steps to take into account the Google authentication:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mugg0vk1s6xri7n6rzrh.png)

The reload last less than a minute.

## 4. Start a new React App

```bash
npx create-react-app agoston-example-react-urql
cd agoston-example-react-urql
npm install --save react-router-dom
npm install --save urql graphql graphql-ws
npm run start
```

## 5. Import Graphql and create the GraphQL client

```javascript
// file ./index.js

// Graphql and urql import
import { createClient, Provider, defaultExchanges, subscriptionExchange } from 'urql';
import { createClient as createWSClient } from 'graphql-ws';


// GraphQL client for websocket subscription
const wsClient = createWSClient({
  fetchOptions: () => ({
    credentials: 'include',
  }),
  url: GRAPHQL_WS_ENDPOINT, // Change the endpoint here with the one of your backend
});

// GraphQL client for standard Graphql requests
const client = createClient({
  fetchOptions: () => ({
    credentials: 'include',
  }),
  url: GRAPHQL_ENDPOINT, // Change the endpoint here with the one of your backend
  exchanges: [
    ...defaultExchanges,
    subscriptionExchange({
      forwardSubscription: (operation) => ({
        subscribe: (sink) => ({
          unsubscribe: wsClient.subscribe(operation, sink),
        }),
      }),
    }),
  ],
});

//Make the GraphQL client available for the application
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Provider value={client}>
    <RouterProvider router={router} />
  </Provider>
);
```

Complete file [on Github](https://github.com/agoston-io/agoston-example-react-urql/blob/master/src/index.js). 

## 6. Add graphQL query to get the session data

```javascript
// file ./routes/root.js

const AgostonSessionData = `query agostonSessionData {
    isSessionAuthenticated
    getCurrentRole
    getCurrentUserId
}`
```

## 7. Execute the query in a component and render

```javascript
// Find the login link in the configuration page, section `Authentication strategies`, field `Auth. URL`.
var AGOSTON_AUTH_GOOGLE="https://<backend_uuid>.<cluster_uuid>.backend.agoston.io/auth/google-oauth20"

Find the login link in the configuration page, section `Authentication URLs`, field `Logout current session`.
var AGOSTON_AUTH_LOGOUT="https://<backend_uuid>.<cluster_uuid>.backend.agoston.io/auth/logout"

function RootWithSessionData() {

    // Execute the query
    const [resultQuery] = useQuery({
      query: AgostonSessionData
    });

    if (resultQuery.fetching) return <p>Loading...</p>;
    if (resultQuery.error) return (
          <div>
            <p>☠ App fails to load | ❌ {resultQuery.error.message}</p>
          </div>
          );

    var sessionData = resultQuery.data;

    return (
        <div >
            <p className={sessionData.isSessionAuthenticated?'banner d-none':'banner'}>🔥 Authenticate yourself <a href={AGOSTON_AUTH_GOOGLE}>here</a>.</p>
            <p className={sessionData.isSessionAuthenticated?'banner':'banner d-none'}>
                🔥 Authenticated as <span className="user-id">user {sessionData.getCurrentUserId}</span> Logout <a href={AGOSTON_AUTH_LOGOUT}>here</a>.
            </p>
        </div>
      );
  };


const Root = () => {
    return (
      <div>
        <RootWithSessionData />
      </div>
    );
}
```

Complete file [on Github](https://github.com/agoston-io/agoston-example-react-urql/blob/master/src/routes/root.js). 

## Conclusion

You now have your application's foundation, including your user's authentication.

The next step will be to create your data model and implement GraphQL requests (query, mutation, subscription).

## Disclaimer

I'm the maker of Agoston.io which is a backend as a service leveraging tried-and-tested open-source solutions. Agoston includes: a single GraphQL endpoint, self-hosting, unified authentication, subscription, dedicated Postgres, custom code, Stripe webhooks, job scheduling, and triggers.