Authentication
Advanced Topics
Integration Guide

Authentication integration guide

ℹ️

This page describes how to add ROQ's authentication to an existing app.
If you use ROQ's AI Assistant (opens in a new tab) to generate your SaaS application, the full authentication is already up and running, and nothing needs to be done.

Introduction

In these getting-started guide you will learn how to level-up your web application with ROQ's advanced authentication and user management capabilties.

💡

In case you are stuck, we are just one message away. Just join the Community Slack (opens in a new tab) and get instant responses from our engineers.

Our VPE, Praveen Koka, shows how to integrate ROQ's authentication into your Next.js application.

🎬

(1) Install NPM packages

Install the following package(s) into your project:

npm install @roq/nextjs

(2) Setup credentials

Login to ROQ Console (opens in a new tab), copy the needed credentials and paste them into the .env file of your web application. You need to add the ROQ_SECRET variable. The value can be generated by running openssl rand -hex 32 on the command line.

You can read more about the credentials here.

(3) Add routes for authentication

ROQ provides a wrapper which adds these four routes into your application: /login, /logout, /session and /callback. You can read more about them here.

Create a new file: pages/api/[...roqAuth].ts with this content. Next.js will automatically detect and import the handler.

import { RoqAuth } from "@roq/nextjs";
 
export default RoqAuth;

(4) Protect frontend pages

You can use requireNextAuth to wrap non-public pages of your application. This disallowes non-authenticated users to open the page and redirects them to the login-page.

import { requireNextAuth } from "@roq/nextjs";
 
const MyPage = function () {
  return <Content>...</Content>;
};
 
export default requireNextAuth({
  redirectIfAuthenticated: true,
  redirectTo: "/login",
})(MyPage);

(5) Protect APIs

On the server-side you can wrap your API handler with the withAuth function to enforce authentication. The function throws an unauthorized error if the user is not authenticated.

import { withAuth } from "@roq/nextjs";
 
async function handler(req: NextApiRequest, res: NextApiResponse) {
  const session = getServerSession(req);
  const user = session.user;
}
 
export default function apiHandler(req: NextApiRequest, res: NextApiResponse) {
  return withAuth(req, res)(handler);
}

What's next

🎉🎉🎉🎉🎉 That’s it! You successfully protected your application. Give it a try and register a new user. Of course, you can individualize your authentication even further: Feature Overview.