Building an AI-Powered Job Description Generator with Next.js and ChatGPT

As a hiring manager or recruiter, writing compelling job descriptions can be a tedious and time-consuming task. You want to accurately convey the role and attract qualified candidates, but it‘s difficult to be creative and engaging while juggling multiple requisitions.

But what if you could automatically generate professional, eye-catching job descriptions in seconds? With the power of AI writing tools like ChatGPT and modern web frameworks like Next.js, it‘s possible to build your own job description generator to streamline your hiring workflow.

In this step-by-step tutorial, we‘ll walk through how to create a job description generator web app using:

  • Next.js and React for the frontend
  • ChatGPT API for natural language generation of the job descriptions
  • TailwindCSS for easy, responsive styling

By the end, you‘ll have a fully-functional app to generate unique job descriptions from a few key inputs about the role. Let‘s get started!

Why Build a Job Description Generator?

Automated job description generation provides several benefits for hiring teams and companies:

  1. Saves time – instantly generate a full description instead of spending hours writing and editing
  2. Enables creativity – get fresh ideas and phrasing from the AI to make your descriptions stand out
  3. Ensures consistency – use the same professional tone and format across all your job postings
  4. Avoids bias – the AI generates neutral, inclusive language to attract diverse applicants
  5. Easy customization – tweak a few parameters to tailor the description to your needs
  6. Cost-effective – no need to pay a copywriter or spend your valuable time writing them yourself

Building your own generator with open-source tools also gives you complete control and ownership over the product vs relying on a third-party service. And it‘s a great way to learn modern web development skills!

Tech Stack Overview

Here‘s a quick primer on the key technologies we‘ll be using:

Next.js

Next.js is a popular React framework for building server-side rendered (SSR) and statically-generated websites. It handles a lot of the configuration and routing so you can focus on building your React front-end. It also has a built-in API route feature that makes it easy to create backend API endpoints within the same Next project.

ChatGPT

ChatGPT is a large language model trained by OpenAI to understand and generate human-like text. By providing it a text "prompt" with instructions, it can output unique, relevant text in response. ChatGPT is extremely versatile – we‘ll use it to generate the job descriptions, but it can be used for any writing task from articles to poetry to code.

TailwindCSS

TailwindCSS is a utility-first CSS framework that provides a set of composable classes to style your HTML elements. Instead of writing custom CSS, you can apply pre-built class names like "text-lg font-bold" to quickly build your UI. Tailwind is a great pairing with React as it allows you to style directly in your JSX.

Project Setup

First, make sure you have Node.js installed on your development machine. Open a terminal and run the following commands to create a new Next.js project:

npx create-next-app@latest job-description-generator
cd job-description-generator
code . 

This will bootstrap a basic Next.js project in a new directory and open it in VS Code.

Next, let‘s install and configure TailwindCSS. Stop the Next dev server and run:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

This installs Tailwind and creates the necessary config files. Open tailwind.config.js and replace its content with:

module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx}",
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

This tells Tailwind to scan your React components for its classes. Finally, add the Tailwind base styles to your global CSS file:

/* styles/globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

Start your Next dev server again with npm run dev and you‘re ready to use Tailwind in your app!

Building the Job Description Form

At the core of our generator is a form to collect the key details about a job to feed into ChatGPT. We‘ll ask for:

  • Job title
  • Company name
  • Location
  • Salary range
  • Required skills and experience
  • Job responsibilities
  • Company culture and benefits

To start, replace the default homepage at pages/index.js with this basic form layout using Tailwind classes for styling:

// pages/index.js
import Head from ‘next/head‘

export default function Home() {
  return (
    <div className="flex min-h-screen flex-col items-center justify-center py-2">
      <Head>
        <title>Job Description Generator</title>
      </Head>

      <main className="flex w-full flex-1 flex-col items-center px-20 text-center">
        <h1 className="text-4xl font-bold mb-8">
          Job Description Generator
        </h1>

        <form className="w-full max-w-lg"> 
          <div className="mb-6">
            <label htmlFor="jobTitle" className="mb-2 block text-left text-gray-900">
              Job Title
            </label>
            <input 
              type="text"
              id="jobTitle"
              className="w-full rounded-lg border border-gray-300 p-2.5 text-gray-900"
              placeholder="Senior Software Engineer"
              required
            />
          </div>

          <div className="mb-6">
            <label htmlFor="company" className="mb-2 block text-left text-gray-900">
              Company
            </label>
            <input
              type="text" 
              id="company"
              className="w-full rounded-lg border border-gray-300 p-2.5 text-gray-900"
              placeholder="ACME Inc."
              required
            />
          </div>

          {/* Add the other form fields */}

          <button
            type="submit"
            className="w-full rounded-lg bg-blue-700 px-5 py-2.5 text-center text-sm font-medium text-white hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300"
          >
            Generate Job Description
          </button>
        </form>
      </main>
    </div>
  )
}

This sets up a clean, accessible form interface with Tailwind utility classes providing the styling. We won‘t wire up the onSubmit handler just yet – first let‘s get our ChatGPT integration working.

Generating Job Descriptions with ChatGPT

To generate the actual job description text, we‘ll send the form data as a prompt to the ChatGPT API. First, sign up for an API key at https://www.openai.com/api/.

Next, create a new file called .env.local in the root directory of your Next project. Add your API key like this:

OPENAI_API_KEY=your_api_key_here

Make sure to add .env.local to your .gitignore so you don‘t accidentally commit your key! Next.js will automatically load this environment variable for use in your app.

Now let‘s create a new API route to handle generating the description. Create a new file pages/api/generate.js and add:

// pages/api/generate.js
import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

export default async function handler(req, res) {
  const { jobTitle, company, location, salary, skills, experience, responsibilities, culture } = req.body;

  const prompt = `Write a job description for a ${jobTitle} role at ${company}, based in ${location}. 

  Key requirements:
  - Salary range: ${salary}
  - Required skills: ${skills}
  - Required experience: ${experience}
  - Core responsibilities: ${responsibilities}
  - Company culture and benefits: ${culture}

  Aim for 200-300 words in a professional and engaging tone that would attract qualified candidates.`;

  const completion = await openai.createCompletion({
    model: "text-davinci-003",
    prompt: prompt,
    temperature: 0.7,
    max_tokens: 500,
  });

  console.log(completion.data.choices[0].text);

  res.status(200).json({ 
    description: completion.data.choices[0].text 
  });
}

Let‘s break this down step-by-step. First, we import the official OpenAI SDK and create a client instance with our API key.

Our handler function expects the form data in the request body. It then constructs a descriptive prompt for ChatGPT with the job details in a human-friendly format.

We call the createCompletion method of the OpenAI client, passing in:

  • The ID of the ChatGPT model to use (text-davinci-003 is one of the most capable)
  • The prompt text we just built
  • A temperature value that controls the "creativity" of the output (higher = more random, lower = more focused/deterministic). 0.7 is a good balance.
  • The maximum number of tokens (roughly 4 characters) for ChatGPT to generate.

The response from ChatGPT will be returned in the API response for use in our frontend.

Integrating the Frontend and Backend

Now that our API is set up, let‘s connect it to the form submission in the UI. Back in pages/index.js, add the following code:

// pages/index.js
import { useState } from ‘react‘;

export default function Home() {
  const [jobDescription, setJobDescription] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();

    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData);

    const response = await fetch(‘/api/generate‘, {
      method: ‘POST‘,
      headers: {
        ‘Content-Type‘: ‘application/json‘,
      },
      body: JSON.stringify(data),
    });

    const { description } = await response.json();
    setJobDescription(description);
  };

  return (
    // Existing JSX
    <form onSubmit={handleSubmit}>
      {/* Form fields */}
    </form>

    {jobDescription && (
      <div className="mt-8">
        <h2 className="text-xl font-bold mb-4">Generated Job Description:</h2>
        <p className="text-left">{jobDescription}</p>
      </div>
    )}
    // Existing JSX
  );
}

In the handleSubmit function, we:

  1. Prevent the default form submission behavior
  2. Extract the form field values into a data object
  3. Send a POST request to our /api/generate endpoint with that data
  4. Parse the response and update the jobDescription state variable

We conditionally render this generated description text below the form. And with that, we have a fully functional job description generator!

Try it out by filling the form with details for a role and clicking "Generate Job Description". You should see a unique, professional description appear within a few seconds! The more details you provide, the higher quality output you‘ll get.

Conclusion and Next Steps

Congratulations – you now have a fully functional job description generator powered by ChatGPT and built with modern web technologies like Next.js and Tailwind! I hope this tutorial helped demystify some of the key concepts and you learned a few new skills in the process.

Some ideas to extend this project:

  • Add more fine-tuned inputs to control the tone, length, and format of the descriptions
  • Persist your generated descriptions in a database and add search/filter capabilities
  • Expand the app to generate other types of recruitment content like interview questions and rejection letters
  • Incorporate other AI models and APIs to assist with other parts of hiring like resume screening

The foundation we built here can be applied to all sorts of AI-powered writing tools – I encourage you to experiment and customize it to your needs!

To dive deeper into the topics we covered, here are some recommended resources:

Feel free to reach out if you have any questions or want to share what you‘ve built! Happy coding!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *