Skip to main content

Vercel / NextJS SDK

With our JavaScript / TypeScript SDK, you can easily integrate ServerlessQ into your application.

The SDK is completely suited for Vercel Users who use NextJS. We will extend it in the future but for now it works with NextJS deployed to Vercel.

Prequisites

The library needs one environment variable:

  • SERVERLESSQ_API_TOKEN

(soon) Checkout our Vercel Integration to set them up automatically.

TLDR;

  1. Install
yarn add @serverlessq/nextjs
npm i @serverlessq/nextjs
pnpm i @serverlessq/nextjs
  1. Import Queue
import { Queue } from "@serverlessq/nextjs";
  1. Create a Queue within a NextJS API
// pages/api/queue
export default Queue(
"SendNewsletter",
"api/queue",
async (req, res) => {
const result = await doSomethingImportant();
console.log("Queue Job", result);
res.send("finished");
},
{ retries: 1, urlToOverrideWhenRunningLocalhost: "https://mock.codes/201" }
);

Now you define your Queue. Your queue exists out of the following options:

  • Name of the queue: SendNewsletter
  • Path to the queue: api/queue
  • Function to execute: async (req, res) => { ... }
  • Options:
    • Retries: How often should failed requests be retried?
    • urlToOverrideWhenRunningLocalhost: When running locally, you can override the URL to the queue. That needs more explanation. Our system runs in the cloud. That means the consumer of your queue (aka this function) needs to be reachable in the internet. Since it is runnign locally you have the option to override this URL with either something like ngrok or some deployed consumer.
  1. Enqueue a Job

You can now import your queue and enqueue a job.

// pages/api/enqueue or getServerSideProps
import { NextApiRequest, NextApiResponse } from "next";
import testQueue from "./queue";

export default async function enqueue(
req: NextApiRequest,
res: NextApiResponse
) {
const result = await testQueue.enqueue({ method: "GET" });
res.send("OK");
}

Here you simply send a job to your queue with a defined HTTP method. Thats it ✨

Tutorial

Let's have a bit more detailed look in a tutorial with example code. You can find the repository here

Lets show you how to get the same functionality step-by-step

Install Dependency

Install the library

We first added @serverlessq/nextjs as a dependency.

yarn add @serverlessq/nextjs

Add Environment Variables

First, you need to sign up on ServerlessQ.

To access your ServerlessQ account you need to add one API key.

  • SERVERLESSQ_API_TOKEN: You can find your API key in your settings

Open your settings and copy the access token.

Settings with API token

Add the value to the .env.local file in your project root. For a proper deployment you need to add them on your provider. For Vercel you can simply do this in the project settings.

Create a Queue

You can either create a queue from code or from the UI. We prefer code in this tutorial so let's create a queue.

Create a new API Route within your NextJS application, e.g. pages/api/queue.

You can have several queues in multiple queue functions.

// pages/api/queue
export default Queue(
"SendNewsletter", // Name of the queue
"api/queue", // Path to this queue
async (req, res) => {
// Handler function. This will be executed once you enqueue a job.
const result = await doSomethingImportant();
console.log("Queue Job", result);
res.send("finished");
},
{ retries: 1, urlToOverrideWhenRunningLocalhost: "https://mock.codes/201" } // Additional optional options
);

Your queue will be created once from this code.

Parameter

You need to define 4 parameter:

  • name: Name of the queue. This needs to be unique within your account
  • path: Path to the queue. We need this to call the correct path.
  • handler: Function to execute. This function will be executed when you enqueue a job.
  • options: Additional options.
    • retries: How often should failed requests be retried?
    • urlToOverrideWhenRunningLocalhost: When running locally, you can override the URL to the queue. This is needed due to the fact that ServerlessQ runs on the cloud. That means your consumer needs to be online. When developing locally you can override the consumer function in case you want to use something like ngrok or a deployed consumer function.

Enqueue Jobs

You can now easily enqueue jobs by importing your created queue and simple call .enqueue(...). You can do this either from getServerSideProps or from another API function. You can't do it from the frontend since you don't want to expose your API key.

// pages/api/enqueue or getServerSideProps
import { NextApiRequest, NextApiResponse } from "next";
import testQueue from "./queue";

export default async function enqueue(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const result = await testQueue.enqueue({ method: "GET" });
res.json({ status: "success", ...result });
} catch (e) {
res.json({ status: "failed" });
}
}

Frontend

The frontend demonstrates the use case of the SDK.

We have two ways of enqueueing a job

Get Server Side Props

You can use getServerSideProps to enqueue a job.

import myQueue from "../pages/api/queue";

export const getServerSideProps = async () => {
const resp = await myQueue.enqueue({ method: "GET" });
console.log(resp);
return {
props: {
...resp,
},
};
};

We simply import the queue and call .enqueue() with the HTTP method.

API Function Call from Client

We can also call the API function from the client. This is useful if you want to enqueue a job from the frontend.

This requires two steps:

  1. Create a new NextJS API Route to enqueue, e.g. pages/api/enqueue
import myQueue from "../pages/api/queue";

export const getServerSideProps = async () => {
const resp = await myQueue.enqueue({ method: "GET" });
console.log(resp);
return {
props: {
...resp,
},
};
};
  1. Call the endpoint from the frontend:
const doSomething = async () => {
setIsLoading(true);
try {
const r = await fetch("/api/enqueue");
console.log(r);
} catch (e) {
console.log(e);
}

setIsLoading(false);
};

Check your Request

Now head over to ServerlessQ to see the details of your request. Go to the queue and open the correct one. You can now see the request you've sent from your example project. Names a unique across your queues.

Example

That's it 🥳

You now have a proper background functionality within your Vercel project.

Types

We have full TypeScript support of course ✨

Local Development

ServerlessQ runs on the cloud. That means if you work locally on a queue and want to test enqueueing jobs you need to override the parameter urlToOverrideWhenRunningLocalhost in the queue options. This url will only be used if the environment variable VERCEL is not set. You can use a service such as ngrok. Ngrok gives you a deployed Webhook URL and you can run a local CLI which listens to all of these incoming requests. This is a great way to test your queue.

Checkout our tutorial on that here

If you need help with that please contact us! 💬

Working with Existing Queues

You have also the opportunity to work with existing queues. If you have created a queue from the ServerlessQ UI and simply want to forward messages you can do that.

// pages/api/existingQueue
import { enqueue } from "@serverlessq/nextjs";
import { NextApiRequest, NextApiResponse } from "next";

export default async function handler(
_req: NextApiRequest,
res: NextApiResponse
) {
try {
const result = await enqueue({
target: // TARGET URL,
method: // HTTP METHOD,
queueId: // QUEUE-ID,
});
res.json({ status: "success", ...result });
} catch (e) {
res.json({ status: "failed" });
}
}

You can use the enqueue function to directly enqueue a job to a certain Queue-ID.