Creating a resume builder with React, NodeJS and AI šŸš€

In this article, you'll learn how to create a resume builder using React, Node.js, and the OpenAI API. What's better to look for a job and say you have build a job resume builder with AI to do so? 🤩

Author:Nevo David
Nevo David

A small request 🄺

I produce content weekly, and your support helps so much to create more content. Please support me by clicking theĀ ā€œLoveā€Ā button. You probably want toĀ ā€œSaveā€Ā this article also, so you can just click both buttons. Thank you very very much! ā¤ļø

Introduction to the OpenAI API

GPT-3 is a type of artificial intelligence program developed by OpenAI that is really good at understanding and processing human language. It has been trained on a huge amount of text data from the internet, which allows it to generate high-quality responses to a wide range of language-related tasks.

For this article we will use OpenAI GPT3.Once the ChatGPT API is out, I will create another article using it šŸ¤—I have been a big fan of OpenAI from the day they released their first API, I have turned to one of the employees and sent them a nice request to get access to the beta version of GPT3, and I got it šŸ˜…

That’s me in Dec 30, 2020, Begging for access.

Novu – the first open-source notification infrastructure

Just a quick background about us. Novu provides a unified API that makes it simple to send notifications through multiple channels, including In-App, Push, Email, SMS, and Chat. With Novu, you can create custom workflows and define conditions for each channel, ensuring that your notifications are delivered in the most effective way possible.

I would be super happy if you could give us a star! And let me also know in the comments ā¤ļø https://github.com/novuhq/novu

Project Setup

Here, I’ll guide you through creating the project environment for the web application. We’ll use React.js for the front end and Node.js for the backend server.

Create the project folder for the web application by running the code below:

mkdir resume-builder
cd resume-builder
mkdir client server

Setting up the Node.js server

Navigate into the server folder and create aĀ package.jsonĀ file.

cd server & npm init -y

Install Express, Nodemon, and the CORS library

npm install express cors nodemon

ExpressJSĀ is a fast, minimalist framework that provides several features for building web applications in Node.js,Ā CORSĀ is a Node.js package that allows communication between different domains, andĀ NodemonĀ is a Node.js tool that automatically restarts the server after detecting file changes.

Create anĀ index.jsĀ file – the entry point to the web server.

touch index.js

Set up a Node.js server using Express.js. The code snippet below returns a JSON object when you visit theĀ http://localhost:4000/apiĀ in your browser.

//\ud83d\udc47\ud83c\udffbindex.js
const express = require("express");
const cors = require("cors");
const app = express();
const PORT = 4000;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());

app.get("/api", (req, res) => {
    res.json({
        message: "Hello world",
    });
});

app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
});

Configure Nodemon by adding the start command to the list of scripts in theĀ package.jsonĀ file. The code snippet below starts the server using Nodemon.

//In server/package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },

Congratulations! You can now start the server by using the command below.

npm start

Setting up the React application

Navigate into the client folder via your terminal and create a new React.js project.

cd client
npx create-react-app ./

Install Axios and React Router.Ā React RouterĀ is a JavaScript library that enables us to navigate between pages in a React application.Ā AxiosĀ is a promise-based Node.js HTTP client for performing asynchronous requests.

npm install axios react-router-dom

Delete the redundant files, such as the logo and the test files from the React app, and update theĀ App.jsĀ file to display Hello World as below.

function App() {
    return (
        
            Hello World!</p>
        </div>
    );
}
export default App;

Navigate into theĀ src/index.cssĀ file and copy the code below. It contains all the CSS required for styling this project.

@import url("https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap");

* {
    font-family: "Space Grotesk", sans-serif;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
form {
    padding: 10px;
    width: 80%;
    display: flex;
    flex-direction: column;
}
input {
    margin-bottom: 15px;
    padding: 10px 20px;
    border-radius: 3px;
    outline: none;
    border: 1px solid #ddd;
}
h3 {
    margin: 15px 0;
}
button {
    padding: 15px;
    cursor: pointer;
    outline: none;
    background-color: #5d3891;
    border: none;
    color: #f5f5f5;
    font-size: 16px;
    font-weight: bold;
    border-radius: 3px;
}
.app {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30px;
}
.app > p {
    margin-bottom: 30px;
}
.nestedContainer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
}
.companies {
    display: flex;
    flex-direction: column;
    width: 39%;
}
.currentInput {
    width: 95%;
}
#photo {
    width: 50%;
}
#addBtn {
    background-color: green;
    margin-right: 5px;
}
#deleteBtn {
    background-color: red;
}
.container {
    min-height: 100vh;
    padding: 30px;
}
.header {
    width: 80%;
    margin: 0 auto;
    min-height: 10vh;
    background-color: #e8e2e2;
    padding: 30px;
    border-radius: 3px 3px 0 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.resumeTitle {
    opacity: 0.6;
}
.headerTitle {
    margin-bottom: 15px;
}
.resumeImage {
    vertical-align: middle;
    width: 150px;
    height: 150px;
    border-radius: 50%;
}
.resumeBody {
    width: 80%;
    margin: 0 auto;
    padding: 30px;
    min-height: 80vh;
    border: 1px solid #e0e0ea;
}
.resumeBodyTitle {
    margin-bottom: 5px;
}
.resumeBodyContent {
    text-align: justify;
    margin-bottom: 30px;
}

Building the application user interface

Here, we’ll create the user interface for the resume builder application to enable users to submit their information and print the AI-generated resume.

Create a components folder within theĀ client/srcĀ folder containing theĀ Home.js,Ā Loading.js,Ā Resume.js,Ā ErrorPage.jsĀ files.

cd client/src
mkdir components
touch Home.js Loading.js Resume.js ErrorPage.js

From the code snippet above:

  • TheĀ Home.jsĀ file renders the form field to enable users to enter the necessary information.
  • TheĀ Loading.jsĀ contains the component shown to the user when the request is pending.
  • TheĀ Resume.jsĀ displays the AI-generated resume to the user.
  • TheĀ ErrorPage.jsĀ is shown when an error occurs.

Update theĀ App.jsĀ file to render the components using React Router.

import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./components/Home";
import Resume from "./components/Resume";

const App = () => {
    return (
        
            
                
                    } />
                    } />
                </Routes>
            </BrowserRouter>
        </div>
    );
};

export default App;

The Home page

Here, you’ll learn how to build a form layout that can send images via HTTP request and dynamically add and remove input fields.

First, update the Loading component to render the code snippet below, shown to the user when the resume is pending.

import React from "react";

const Loading = () => {
    return (
        
            Loading, please wait...</h1>
        </div>
    );
};

export default Loading;

Next, update theĀ ErrorPage.jsĀ file to display the component below when users navigate directly to the resume page.

import React from "react";
import { Link } from "react-router-dom";

const ErrorPage = () => {
    return (
        
            
                You've not provided your details. Kindly head back to the{" "}
                homepage</Link>.
            </h3>
        </div>
    );
};

export default ErrorPage;

Copy the code snippet below into theĀ Home.jsĀ file

import React, { useState } from "react";
import Loading from "./Loading";

const Home = () => {
    const [fullName, setFullName] = useState("");
    const [currentPosition, setCurrentPosition] = useState("");
    const [currentLength, setCurrentLength] = useState(1);
    const [currentTechnologies, setCurrentTechnologies] = useState("");
    const [headshot, setHeadshot] = useState(null);
    const [loading, setLoading] = useState(false);

    const handleFormSubmit = (e) => {
        e.preventDefault();
        console.log({
            fullName,
            currentPosition,
            currentLength,
            currentTechnologies,
            headshot,
        });
        setLoading(true);
    };
    //\ud83d\udc47\ud83c\udffb Renders the Loading component you submit the form
    if (loading) {
        return ;
    }
    return (
        
            Resume Builder</h1>
            Generate a resume with ChatGPT in few seconds</p>
            
                Enter your full name</label>
                 setFullName(e.target.value)}
                />
                
                    
                        Current Position</label>
                         setCurrentPosition(e.target.value)}
                        />
                    </div>
                    
                        For how long? (year)</label>
                         setCurrentLength(e.target.value)}
                        />
                    </div>
                    
                        Technologies used</label>
                         setCurrentTechnologies(e.target.value)}
                        />
                    </div>
                </div>
                Upload your headshot image</label>
                 setHeadshot(e.target.files[0])}
                />

                CREATE RESUME</button>
            </form>
        </div>
    );
};

export default Home;

The code snippet renders the form field below. It accepts the full name and current work experience – (year, position, title) and allows the user to upload a headshot image via the form field.

Lastly, you need to accept the user’s previous work experience. So, add a new state that holds the array of job descriptions.

const [companyInfo, setCompanyInfo] = useState([{ name: "", position: "" }]);

Add the following functions which help with updating the state.

//\ud83d\udc47\ud83c\udffb updates the state with user's input
const handleAddCompany = () =>
    setCompanyInfo([...companyInfo, { name: "", position: "" }]);

//\ud83d\udc47\ud83c\udffb removes a selected item from the list
const handleRemoveCompany = (index) => {
    const list = [...companyInfo];
    list.splice(index, 1);
    setCompanyInfo(list);
};
//\ud83d\udc47\ud83c\udffb updates an item within the list
const handleUpdateCompany = (e, index) => {
    const { name, value } = e.target;
    const list = [...companyInfo];
    list[index][name] = value;
    setCompanyInfo(list);
};

TheĀ handleAddCompanyĀ updates theĀ companyInfoĀ state with the user’s input,Ā handleRemoveCompanyĀ is used to remove an item from the list of data provided, and theĀ handleUpdateCompanyĀ updates the item properties – (name and position) within the list.

Next, render the UI elements for the work experience section.

return (
    
        Companies you've worked at</h3>
        
            {/*--- other UI tags --- */}
            {companyInfo.map((company, index) => (
                
                    
                        Company Name</label>
                         handleUpdateCompany(e, index)}
                        />
                    </div>
                    
                        Position Held</label>
                         handleUpdateCompany(e, index)}
                        />
                    </div>

                    
                        {companyInfo.length - 1 === index && companyInfo.length < 4 && (
                            
                                Add
                            </button>
                        )}
                        {companyInfo.length > 1 && (
                             handleRemoveCompany(index)}>
                                Del
                            </button>
                        )}
                    </div>
                </div>
            ))}

            CREATE RESUME</button>
        </form>
    </div>
);

The code snippet maps through the elements within theĀ companyInfoĀ array and displays them on the webpage. TheĀ handleUpdateCompanyĀ function runs when a user updates the input field, thenĀ handleRemoveCompanyĀ removes an item from the list of elements, and theĀ handleAddCompanyĀ adds a new input field.

The Resume page

This page shows the resume generated from the OpenAI API in a printable format. Copy the code below into theĀ Resume.jsĀ file. We’ll update its content later in this tutorial.

import React from "react";
import ErrorPage from "./ErrorPage";

const Resume = ({ result }) => {
    if (JSON.stringify(result) === "{}") {
        return ;
    }

    const handlePrint = () => alert("Print Successful!");
    return (
        <>
            Print Page</button>
            
                Hello!</p>
            </main>
        </>
    );
};

How to submit images via forms in Node.js

Here, I’ll guide you on how to submit the form data to the Node.js server. Since the form contains images, we’ll need to set upĀ MulterĀ on the Node.js server.

šŸ’”Ā MulterĀ is a Node.js middleware used for uploading files to the server.

Setting up Multer

Run the code below to install Multer

npm install multer

Ensure the form on the frontend application has the method andĀ encTypeĀ attributes, because Multer only process forms which are multpart.

</form>

Import the Multer and the Node.js path packages into theĀ index.jsĀ file

const multer = require("multer");
const path = require("path");

Copy the code below into theĀ index.jsĀ to configure Multer.

app.use("/uploads", express.static("uploads"));

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, "uploads");
    },
    filename: (req, file, cb) => {
        cb(null, Date.now() + path.extname(file.originalname));
    },
});

const upload = multer({
    storage: storage,
    limits: { fileSize: 1024 * 1024 * 5 },
});
  • From the code snippet above:
    • TheĀ app.use()Ā function enables Node.js to serve the contents of anĀ uploadsĀ folder. The contents refer to static files such as images, CSS, and JavaScript files.
    • TheĀ storageĀ variable containingĀ multer.diskStorageĀ gives us full control of storing the images. The function above stores the images in the upload folder and renames the image to its upload time (to prevent filename conflicts).
    • The upload variable passes the configuration to Multer and set a size limit of 5MB for the images.

Create theĀ uploadsĀ folder on the server. This is where the images will be saved.

mkdir uploads

How to upload images to a Node.js server

Add a route that accepts all the form inputs from the React app. TheĀ upload.single("headshotImage")Ā function adds the image uploaded via the form to theĀ uploadsĀ folder.

app.post("/resume/create", upload.single("headshotImage"), async (req, res) => {
    const {
        fullName,
        currentPosition,
        currentLength,
        currentTechnologies,
        workHistory,
    } = req.body;

    console.log(req.body);

    res.json({
        message: "Request successful!",
        data: {},
    });
});

Update theĀ handleFormSubmitĀ function within theĀ Home.jsĀ component to submit the form data to the Node.js server.

import axios from "axios";

const handleFormSubmit = (e) => {
    e.preventDefault();

    const formData = new FormData();
    formData.append("headshotImage", headshot, headshot.name);
    formData.append("fullName", fullName);
    formData.append("currentPosition", currentPosition);
    formData.append("currentLength", currentLength);
    formData.append("currentTechnologies", currentTechnologies);
    formData.append("workHistory", JSON.stringify(companyInfo));
    axios
        .post("http://localhost:4000/resume/create", formData, {})
        .then((res) => {
            if (res.data.message) {
                console.log(res.data.data);
                navigate("/resume");
            }
        })
        .catch((err) => console.error(err));
    setLoading(true);
};

The code snippet above creates a key/value pair representing the form fields and their values which are sent via Axios to the API endpoint on the server. If there is a response, it logs the response and redirect the user to the Resume page.

How to communicate with the OpenAI API in Node.js

In this section, you’ll learn how to communicate with the OpenAI API within the Node.js server.We’ll send the user’s information to the API to generate a profile summary, job description, and achievements or related activities completed at the previous organisations. To accomplish this:

Install the OpenAI API Node.js library by running the code below.

npm install openai

Log in or create an OpenAI accountĀ here.

ClickĀ PersonalĀ on the navigation bar and selectĀ View API keysĀ from the menu bar to create a new secret key.

Copy the API Key somewhere safe on your computer; we’ll use it shortly.

Configure the API by copying the code below into theĀ index.jsĀ file.

const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
    apiKey: "",
});

const openai = new OpenAIApi(configuration);

Create a function that accepts a text (prompt) as a parameter and returns an AI-generated result.

const GPTFunction = async (text) => {
    const response = await openai.createCompletion({
        model: "text-davinci-003",
        prompt: text,
        temperature: 0.6,
        max_tokens: 250,
        top_p: 1,
        frequency_penalty: 1,
        presence_penalty: 1,
    });
    return response.data.choices[0].text;
};

The code snippet above uses theĀ text-davinci-003Ā model to generate an appropriate answer to the prompt. The other key values helps us generate the specific type of response we need.

Update theĀ /resume/createĀ route as done below.

app.post("/resume/create", upload.single("headshotImage"), async (req, res) => {
    const {
        fullName,
        currentPosition,
        currentLength,
        currentTechnologies,
        workHistory, //JSON format
    } = req.body;

    const workArray = JSON.parse(workHistory); //an array

    //\ud83d\udc47\ud83c\udffb group the values into an object
    const newEntry = {
        id: generateID(),
        fullName,
        image_url: `http://localhost:4000/uploads/${req.file.filename}`,
        currentPosition,
        currentLength,
        currentTechnologies,
        workHistory: workArray,
    };
});

The code snippet above accepts the form data from the client, converts theĀ workHistoryĀ to its original data structure (array), and puts them all into an object.

Next, create the prompts you want to pass into theĀ GPTFunction.

//\ud83d\udc47\ud83c\udffb loops through the items in the workArray and converts them to a string
const remainderText = () => {
    let stringText = "";
    for (let i = 0; i < workArray.length; i++) {
        stringText += ` ${workArray[i].name} as a ${workArray[i].position}.`;
    }
    return stringText;
};
//\ud83d\udc47\ud83c\udffb The job description prompt
const prompt1 = `I am writing a resume, my details are \n name: ${fullName} \n role: ${currentPosition} (${currentLength} years). \n I write in the technolegies: ${currentTechnologies}. Can you write a 100 words description for the top of the resume(first person writing)?`;
//\ud83d\udc47\ud83c\udffb The job responsibilities prompt
const prompt2 = `I am writing a resume, my details are \n name: ${fullName} \n role: ${currentPosition} (${currentLength} years). \n I write in the technolegies: ${currentTechnologies}. Can you write 10 points for a resume on what I am good at?`;
//\ud83d\udc47\ud83c\udffb The job achievements prompt
const prompt3 = `I am writing a resume, my details are \n name: ${fullName} \n role: ${currentPosition} (${currentLength} years). \n During my years I worked at ${
    workArray.length
} companies. ${remainderText()} \n Can you write me 50 words for each company seperated in numbers of my succession in the company (in first person)?`;

//\ud83d\udc47\ud83c\udffb generate a GPT-3 result
const objective = await GPTFunction(prompt1);
const keypoints = await GPTFunction(prompt2);
const jobResponsibilities = await GPTFunction(prompt3);
//\ud83d\udc47\ud83c\udffb put them into an object
const chatgptData = { objective, keypoints, jobResponsibilities };
//\ud83d\udc47\ud83c\udffblog the result
console.log(chatgptData);
  • From the code snippet above:
    • TheĀ remainderTextĀ function loops through the array of work history and returns a string data type of all work experiences.
    • Then, there are three prompts with instructions on what is needed from the GPT-3 API.
    • Next, you store the results in an object and log them to the console.

Lastly, return the AI-generated result and the information the users entered. You can also create an array representing the database that stores results as done below.

let database = [];

app.post("/resume/create", upload.single("headshotImage"), async (req, res) => {
    //...other code statements
    const data = { ...newEntry, ...chatgptData };
    database.push(data);

    res.json({
        message: "Request successful!",
        data,
    });
});

Displaying the response from the OpenAI API

In this section, I’ll guide you through displaying the results generated from the OpenAI API in a readable and printable format on a web page.

Create a React state within theĀ App.jsĀ file. The state will hold the results sent from the Node.js server.

import React, { useState } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./components/Home";
import Resume from "./components/Resume";

const App = () => {
    //\ud83d\udc47\ud83c\udffb state holding the result
    const [result, setResult] = useState({});

    return (
        
            
                
                    } />
                    } />
                </Routes>
            </BrowserRouter>
        </div>
    );
};

export default App;

From the code snippet above, onlyĀ setResultĀ is passed as a prop into the Home component and onlyĀ resultĀ for the Resume component.Ā setResultĀ updates the value of the result once the form is submitted and the request is successful, whileĀ resultĀ contains the response retrieved from the server, shown within the Resume component.

Update theĀ resultĀ state within the Home component after the form is submitted and the request is successful.

const Home = ({ setResult }) => {
    const handleFormSubmit = (e) => {
        e.preventDefault();

        //...other code statements
        axios
            .post("http://localhost:4000/resume/create", formData, {})
            .then((res) => {
                if (res.data.message) {
                    //\ud83d\udc47\ud83c\udffb updates the result object
                    setResult(res.data.data);
                    navigate("/resume");
                }
            })
            .catch((err) => console.error(err));
        setLoading(true);
    };
    return </div>;
};

Update the Resume component as done below to preview the result within the React app.

import ErrorPage from "./ErrorPage";

const Resume = ({ result }) => {
    //\ud83d\udc47\ud83c\udffb function that replaces the new line with a break tag
    const replaceWithBr = (string) => {
        return string.replace(/\n/g, "");
    };

    //\ud83d\udc47\ud83c\udffb returns an error page if the result object is empty
    if (JSON.stringify(result) === "{}") {
        return ;
    }

    const handlePrint = () => alert("Printing");

    return (
        <>
            Print Page</button>
            
                
                    
                        {result.fullName}</h1>
                        
                            {result.currentPosition} ({result.currentTechnologies})
                        </p>
                        
                            {result.currentLength}year(s) work experience
                        </p>
                    </div>
                    
                        
                    </div>
                </header>
                
                    
                        PROFILE SUMMARY</h2>
                        
                    </div>
                    
                        WORK HISTORY</h2>
                        {result.workHistory.map((work) => (
                            
                                {work.name}</span> -{" "}
                                {work.position}
                            </p>
                        ))}
                    </div>
                    
                        JOB PROFILE</h2>
                        
                    </div>
                    
                        JOB RESPONSIBILITIES</h2>
                        
                    </div>
                </div>
            </main>
        </>
    );
};

The code snippet above displays the result on the webpage according to the specified layout. The functionĀ replaceWithBrĀ replaces every new line (\n) with a break tag, and theĀ handlePrintĀ function will enable users to print the resume.

How to print React pages using the React-to-print package

Here, you’ll learn how to add a print button to the web page that enables users to print the resume via theĀ React-to-printĀ package.

šŸ’”Ā React-to-printĀ  is a simple JavaScript package that enables you to print the content of a React component without tampering with the component CSS styles.

Run the code below to install the package

npm install react-to-print

Import the library within theĀ Resume.jsĀ file and add theĀ useRefĀ hook.

import { useReactToPrint } from "react-to-print";
import React, { useRef } from "react";

Update theĀ Resume.jsĀ file as done below.

const Resume = ({ result }) => {
    const componentRef = useRef();

    const handlePrint = useReactToPrint({
        content: () => componentRef.current,
        documentTitle: `${result.fullName} Resume`,
        onAfterPrint: () => alert("Print Successful!"),
    });
    //...other function statements
    return (
        <>
            Print Page</button>
            
                {/*---other code statements---*/}
            </main>
        </>
    );
};

TheĀ handlePrintĀ function prints the elements within theĀ componentRef – main tag, sets the document’s name to the user’s full name, and runs the alert function when a user prints the form.

Congratulations! You’ve completed the project for this tutorial.

Here is a sample of the result gotten from the project:

Conclusion

So far, you’ve learnt:

  • what OpenAI GPT-3 is,
  • how to upload images via forms in a Node.js and React.js application,
  • how to interact with the OpenAI GPT-3 API, and
  • how to print React web pages via the React-to-print library.

This tutorial walks you through an example of an application you can build using the OpenAI API. With the API, you can create powerful applications useful in various fields, such as translators, Q&A, code explanation or generation, etc.

The source code for this tutorial is available here:

https://github.com/novuhq/blog/tree/main/resume-builder-with-react-chatgpt-nodejs

Thank you for reading!

Help me out!

If you feel like this article helped you, I would be super happy if you could give us a star! And let me also know in the comments ā¤ļø

https://github.com/novuhq/novu

Read More

You’re five minutes away from your first Novu-backed notification

Create a free account, send your first notification, all before your coffee gets cold... no credit card required.