A company wiki is a knowledge hub where organization-specific information can be easily accessed by the individuals working in an organization. Information in the hub can be related to engineering operations, hiring procedures, employee information, and other company-specific information. Creating and maintaining a company wiki can be complex, but tools like GraphQL and Hygraph (previously GraphCMS) can make it easier.
GraphQL is a query language for APIs that allows you to request and fetch only the data that you want.
Hygraph is a cloud platform for creating databases, tables, and powerful GraphQL APIs. It allows you to create content on the fly with features such as text editors, workflows, and advanced roles.
In this tutorial, you’ll learn to create an internal company wiki from scratch. The backend and content management will be implemented with Hygraph, and the frontend with Next.js.
#Architecture
For this tutorial, you’ll create four data models: employee data, a business glossary, company policy, and video courses. The employee data will be fetched from an external source like BambooHR, and the assets for video courses will be hosted on Cloudinary. Finally, you’ll use GraphQL APIs to fetch the data from Hygraph, and the data will be presented on a Next.js frontend website.
#Prerequisites
To follow this tutorial, you'll need to have Node.JS v16 and npm v8 installed on your system.
#Setting Up Hygraph
The first thing you need to do is set up the backend. To start with Hygraph, sign up for an account if you don’t already have one.
On your Hygraph dashboard, create a new blank project, and fill in the required details by giving it a name, a region, and an optional description.
Once your project is set up, you can create the schemas.
#Creating Models in Hygraph
What tables are to a relational database database, models are to Hygraph. In Hygraph, you can create models and add fields to them.
To create a model, click Schema in the left sidebar to open the schema editor.
Creating the Company Policies Model
To create a model for storing company policies, click on Create Model button, and give the model the display name "Company Policy".
Click the Create Model button, then add the following fields to your model by clicking the appropriate tile in the right-hand column and giving it the specified name:
- Title, a Single line text field.
- Description, a Markdown field.
Creating the Business Glossaries Model
Follow the same steps you followed to create the Company Policy model to create a model for storing business glossaries. Give it the display name "Business Glossary", and add the following fields to it:
- Title, a Single line text field.
- Description, a Multi-line text field.
Creating the Course Videos Model
While you can upload your assets to Hygraph, for the purposes of this tutorial, let’s suppose that you want to host your assets on a third-party platform like Cloudinary. In this case, before you can set up the course videos model, you need to install the Cloudinary app on Hygraph. Follow Connect your Hygraph project to Cloudinary through the end of the "Install the Cloudinary App" section.
Once you have connected Cloudinary with Hygraph, create a model for storing course videos. Give it the display name "Course Video", and add the following fields to it:
- Title, a Single line text field.
- Video, a Cloudinary Asset field.
Creating Employees Model
For the employees, suppose that you want to fetch the data from another platform, like BambooHR. Hygraph allows you to fetch data from remote sources through a process known as content federation.
To get data from a remote source like BambooHR, create an account on BambooHR and add some employee-related data. On fresh signup, BambooHR will add some default data for you.
Once you have signed up for BambooHR and added employee information, click on the Profile button in the top right corner and select API Keys from the dropdown menu.
Create a new API key by giving it a name. Make note of the key and keep it somewhere safe, as you’ll be using it while setting up a remote source in Hygraph:
Next, to see the data sent by the BambooHR API, refer to the BambooHR API Authentication docs and then send a GET request to https://api.bamboohr.com/api/gateway.php/<YOUR_BAMBOOHR_DOMAIN_NAME>/v1/employees/<EMPLOYEE_ID>?fields=firstName,lastName,gender,jobTitle
using an HTTP client like Postman.
<YOUR_BAMBOOHR_DOMAIN_NAME>
, <EMPLOYEE_ID>
, and <YOUR_BAMBOOHR_API_KEY>
in the above request.If the employee ID exists, you’ll get a response containing the fields you passed in the request URL.
On Hygraph dashboard, visit the Schema tab in the left sidebar and then add a new Remote Sources for BambooHR by adding the following details:
- Display Name: BambooHR
- Type: REST
- BaseURL:
https://api.bamboohr.com/api/gateway.php/<YOUR_BAMBOOHR_DOMAIN>/v1
- Headers:
Accept: application/json and Authorization: Bearer <YOUR_BAMBOOHR_API_KEY>
When connecting to a remote API, you can specify the shape of the response coming from the API with the help of a custom type definition. Still on the remote source form, scroll down and add the BambooHREmployee
type with the following fields under the Custom type definition field:
type BambooHrEmployee {firstName: Stringgender: Stringid: StringjobTitle: StringlastName: String}
Save the settings for the remote source, and create a new model for storing employee information. Give it the display name of "Employee", and add the following fields to it:
- BambooHR ID, a Single line text field
External, a REST field. For this field, add the following details:
- Display name: External
- Remote source: BambooHR
- Method: GET
- Return type: BambooHREmployee
- Path:
/employees/{{doc.bambooHrId}}?fields=firstName,lastname,gender,jobTitle
In the path, the {{doc.bambooHrId}}
is the value from the BambooHR ID field.
That’s it. The models are set, and you can now add data to them.
#Adding Data to Content Type
For the company wiki, you need to add data to the models. This data will eventually be shown on the frontend.
To add data to the models, click on Content in the left sidebar, and then add some data and external data sources, such as Cloudinary and BambooHR. Select the model to which you're adding the data, and then click Add entry. Fill in the fields that you created previously, then Save & add another until you've populated the model with data. When you're done, click Save & publish. Do this for each model.
#Setting Up Permissions for the Content API
By default, access to the Content API is forbidden. To get the data from Hygraph, you'll need to set up permissions.
To do so, first, visit the Project Settings in the left sidebar. Click on API Access under the ACCESS header. You’ll be provided with the GraphQL endpoint for the Content API. Make note of this, as you’ll use this endpoint to access the content.
Instead of providing public access to the API, you can protect it with an authentication token and add permissions to it. To do so, visit Project settings in the left sidebar, then click on Create token under the Permanent Auth Tokens section:
Fill in the details for your token by providing it a name, a default stage of your choice for content delivery, and an optional description:
Click Create & configure permissions to create your token. You'll be taken to the Create Permissions page, which displays the token at the top. Make note of this token, as you’ll be using it while fetching the content from the frontend:
Configure the permissions for the Auth token that you just created by clicking the Create permission:
For this app, you only want to allow read access to the content. Check the Read rule for all of the models in all locales, which will allow read access to every model in Hygraph.
With that, you can now access the contents in models using GraphQL queries. To see the data sent by Hygraph, open Postman, visit Auth tab, select Bearer Token as the type, and add the Hygraph auth token as the token's value:
Finally, send the following queries to get data for each model:
For the employees model:
query {employees {idbambooHrIdexternal {idfirstNamelastNamegenderjobTitle}}}
For the company policy model:
query {companyPolicies {idtitledescription}}
For the business glossary model:
query {businessGlossaries {idtitledescription}}
For the video course model:
query {courseVideos {idtitlevideo}}
The backend setup for Hygraph is complete, and now you can set up the frontend to consume data from the backend.
#Setting Up the Frontend
You are now ready to build the Next.js frontend website for the company wiki. To create a Next.js project, run the following command in your terminal:
npx create-next-app@latest
On the terminal, when you are asked about the project‘s name, set it to "company-wiki". After that, all the npm dependencies will be installed.
After the installation is complete, navigate into the company-wiki
directory and start the Next.js development server by running the following commands in your terminal:
cd company-wikinpm run dev
This will start the development server on port 3000 and take you to localhost:3000. The first view of the Next.js website will look like this:
For this application, you need the following npm dependencies:
- Apollo Client, which is a fully-featured GraphQL client with caching.
- GraphQL Wrapper, which is a JavaScript implementation for GraphQL.
- Marked, a low-level compiler for parsing Markdown.
Install the above dependencies by running the following command in your terminal:
npm i @apollo/client graphql marked
Since everyone likes to style their app in their own way, this tutorial will skip styling the app, and instead concentrate on core functionality.
#Setting Up the GraphQL Apollo Client
You need to set up a GraphQL Apollo Client to communicate with the Hygraph Content API.
To do so, first, create a config
directory in the project’s root directory. Then, in the config
directory, create a file called apolloClient.js
and add the following code to it:
// 1import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";import { setContext } from "@apollo/client/link/context";// 2const httpLink = createHttpLink({uri: process.env.NEXT_PUBLIC_HYGRAPH_CONTENT_API_ENDPOINT,});// 3const authLink = setContext((_, { headers }) => {return {headers: {...headers,authorization: `Bearer ${process.env.NEXT_PUBLIC_HYGRAPH_PERMANENTAUTH_TOKEN}`,},};});// 4export const client = new ApolloClient({link: authLink.concat(httpLink),cache: new InMemoryCache(),});
In the above code:
- You import the required NPM packages.
- You create
httpLink
, in which you specify the base URL of the Hygraph Content API endpoint. - You create
authLink
, in which you specify theauthorization
header for communicating with the Hygraph Content API. - You define and export the ApolloClient instance (
client
) in which you pass an object withlink
andcache
properties.
Next, create a .env
file in the root directory and add the following environment variables to it:
NEXT_PUBLIC_HYGRAPH_CONTENT_API_ENDPOINT=<YOUR_HYGRAPH_CONTENT_API_ENDPOINT>NEXT_PUBLIC_HYGRAPH_PERMANENTAUTH_TOKEN=<YOUR_HYGRAPH_PERMANENTAUTH_TOKEN>
YOUR_HYGRAPH_CONTENT_API_ENDPOINT
with your Hygraph Content API endpoint, which is located in Project Settings / Access / API Access, and <YOUR_HYGRAPH_PERMANENTAUTH_TOKEN>
with your Hygraph permanent auth key, which is located in Project Settings / Access / API Access / Permanent Auth Tokens.Open the _app.js
file in the pages
directory and replace the existing code with the following code:
// 1import { ApolloProvider } from "@apollo/client";import { client } from "../config/apolloClient";function MyApp({ Component, pageProps }) {return (// 2<ApolloProvider client={client}><Component {...pageProps} /></ApolloProvider>);}export default MyApp;
In the above code:
- You import the
ApolloProvider
from the@apollo/client
library and theclient
object that you created earlier. - You wrap the
Component
withApolloProvider
, which allows you to access custom hooks and functions defined by@apollo/client
anywhere in your Next.js application.
Creating the Company Wiki Home Page
Open the index.js
file in the pages
directory and replace the existing code with the following code:
import Link from "next/link";export default function HomePage() {return (<><div className="mb-4"><h1>Welcome to Company Wiki</h1></div><div className="d-flex flex-column"><Link href="/employees" passHref><a className="mb-3">Employees</a></Link><Link href="/company-policies" passHref><a className="mb-3">Company Policies</a></Link><Link href="/business-glossary" passHref><a className="mb-3">Business Glossary</a></Link><Link href="/course-videos" passHref><a className="mb-3">Course Videos</a></Link></div></>);}
In the code, you define and export the HomePage
component, in which you provide links to Employees, Company Policies, Business Glossary, and Course Videos.
Save your progress and visit localhost:3000, where you should see something similar to this:
Note that because styling has been left to the reader, your page may look slightly different. However, the core aspects of it—the title and the links to the pages—should be present.
Creating the Employees Page
Create an employees.js
file in the pages
directory and paste in the following code:
// 1import Link from "next/link";import { gql, useQuery } from "@apollo/client";// 2export default function EmployeesPage() {// 3const query = gql`{employees {idbambooHrIdexternal {idfirstNamelastNamegenderjobTitle}}}`;// 4const { loading, error, data } = useQuery(query);// 5if (!loading && !error && data) {return (<><Link href="/" passHref><a>Home</a></Link><div><h1>Employees</h1></div><div>{data.employees.map((employee) => (<div key={employee.id}><h2>{employee.external.firstName} {employee.external.lastName}</h2>{employee.external.gender && <p>{employee.external.gender}</p>}<p>{employee.external.jobTitle}</p></div>))}</div></>);}}
In the above code:
- You import the required npm packages.
- You define and export the
EmployeePage
component. - You define the GraphQL query (
query
) for getting the employees. - You call the
useQuery
hook by passing thequery
to it and getting the values forloading
,error
, anddata
. - You return the UI for the
EmployeePage
component.
Save your progress and visit localhost:3000/employees, and you’ll get the following result:
The explanation above is how each page is created. The numbered steps are the same, and all that changes is the name of the component in steps two and five. As such, while the full code for each page is given, the remaining pages won't have an explanation after them.
Creating the Company Policies Page
Create a company-policies.js
file in the pages
directory and add the following code to it:
// 1import Link from "next/link";import { marked } from "marked";import { gql, useQuery } from "@apollo/client";// 2export default function CompanyPoliciesPage() {// 3const query = gql`{companyPolicies {idtitledescription}}`;// 4const { loading, error, data } = useQuery(query);// 5if (!loading && !error && data) {return (<><Link href="/" passHref><a>Home</a></Link><div className="mb-5 mt-3"><h1>Company Policy</h1></div><div className="d-flex flex-column">{data.companyPolicies.map((policy) => (<div key={policy.id} className="mb-3"><h2 className="h4">{policy.title}</h2>{policy.description && (<divdangerouslySetInnerHTML={{__html: marked.parse(policy.description),}}/>)}</div>))}</div></>);}}
After saving your progress, visit localhost:3000/company-policies to see the result.
Creating Business Glossary Page
Create a file called business-glossary.js
in the pages
directory. Add the following code to it:
// 1import Link from "next/link";import { gql, useQuery } from "@apollo/client";// 2export default function BusinessGlossariesPage() {// 3const query = gql`{businessGlossaries {idtitledescription}}`;// 4const { loading, error, data } = useQuery(query);// 5if (!loading && !error && data) {return (<><Link href="/" passHref><a>Home</a></Link><div className="mb-5 mt-3"><h1>Business Glossary</h1></div><div className="d-flex flex-column">{data.businessGlossaries.map((term) => (<div key={term.id} className="mb-3"><h2 className="h4">{term.title}</h2><p>{term.description}</p></div>))}</div></>);}}
Visit localhost:3000/business-glossary to see the result.
Creating the Course Videos Page
Create course-videos.js
in the pages
directory, and add the following code to it:
// 1import Link from "next/link";import { gql, useQuery } from "@apollo/client";// 2export default function CourseVideosPage() {// 3const query = gql`{courseVideos {idtitlevideo}}`;// 4const { loading, error, data } = useQuery(query);// 5if (!loading && !error && data) {return (<><Link href="/" passHref><a>Home</a></Link><div className="mb-5 mt-3"><h1>Course Videos</h1></div><div className="d-flex flex-column">{data.courseVideos.map((course) => (<div key={course.id} className="mb-3"><h2 className="h4">{course.title}</h2><p>{course?.video?.context?.custom?.caption ?? ""}</p>{course?.video?.url && (<imgclassName="img-fluid w-100 mb-3 rounded"src={course.video.url}alt={course.video?.context?.custom?.caption ?? ""}/>)}</div>))}</div></>);}}
When you save your progress and visit localhost:3000/course-videos, you’ll get the following result:
#Deploying to Vercel (Optional)
As a bonus, you can also deploy your company wiki to a platform like Vercel. You'll need a Vercel account for this part of the tutorial.
To do so, initialize a Git repository in your local project directory, then commit and push the changes to an upstream GitHub repository.
Import your repository to Vercel.
Vercel will automatically detect the framework. Add the project's environment variables and their respective values, then click on Deploy to start the build:
Once the build is complete, you’ll see the deployment URL.
Finally, visit the deployment URL and you’ll see your Next.js website.
#Conclusion
In this tutorial, you learned to create an internal company wiki from scratch. You implemented the backend and content management with Hygraph, and the frontend with Next.js. You also learned to create and fetch data from a remote source in Hygraph. Finally, you learned to manage assets on a third-party host like Cloudinary.
The entire source code for this tutorial is available in this GitHub repository.
Blog Author