In this article
December 2, 2026
December 2, 2026

How to add authentication to a Remix SaaS app

Add auth to a Remix or React Router SaaS app with WorkOS AuthKit: sessions, protected routes, organizations, enterprise SSO, and SCIM.

Explore with AI
Open in ChatGPT
Open in Claude
Open in Perplexity

To add authentication to a Remix SaaS app with WorkOS AuthKit, install the AuthKit Remix SDK (@workos-inc/authkit-remix), enable Remix's single fetch, add a callback route and a sign-in route, run authkitLoader in your root loader, and check the session inside every loader and action that touches data. For a B2B product you then add organizations, roles, enterprise SSO, and SCIM directory sync on the same integration, so you do not replace your login when the first enterprise customer asks for SAML.

This guide builds that setup step by step with TypeScript: sessions in loaders and actions, protected routes and mutations, organizations and roles for multi-tenant apps, and the part where B2B differs, enterprise SSO and SCIM.

!!Which Remix is this for? This guide is for Remix v2 and uses the AuthKit Remix SDK. Remix v2 is built on React Router, and React Router v7 is its next major version. React Router v8 was announced on June 17, 2026, and Remix v2 reached end of life with that release. Apps that moved to React Router use a different WorkOS SDK, @workos-inc/authkit-react-router, whose helpers are similar but not identical. For those apps, use the React Router version of this guide. Remix 3 is a separate framework and is not covered here.!!

What should you look for in authentication for a Remix app?

Look for an auth layer that works where Remix code runs: in server-side loaders and actions, with sessions held in encrypted cookies. An SDK built for client-only single-page apps tends to fit awkwardly, because the data your routes return has to be authorized on the server before it reaches the browser.

  • Session reads in loaders and actions. You should be able to get the current user inside any loader or action without a client round trip.
  • Session refresh on every request. Access tokens are short-lived, so something that runs on each request, such as the root loader, should refresh them.
  • Checks that work with nested routes. Remix runs the loaders of all matched routes in parallel, so a check in a parent layout loader does not stop a child loader from running. Every loader and action needs its own check.
  • Cookie and sign-out handling. Look for encrypted, HTTP-only session cookies and a sign-out that ends the session at the provider, not only in your own cookie.
  • Tenant context in the session. If your product has customers and not only users, the active organization, role, and permissions should arrive with the session.

The @workos-inc/authkit-remix package is built around that model. For a comparison of providers on these criteria, see Top 5 authentication solutions for secure Remix apps in 2026.

When does a B2B app need more than social login?

Social login and email and password cover many apps. They stop being enough when a customer's security team gets involved. A buyer may require sign-in through their own identity provider (Okta, Microsoft Entra ID, Google Workspace) over SAML or OIDC. They may want accounts created and removed automatically from their directory through SCIM. Different customers may need different roles, and one person may belong to more than one customer. The person configuring all of this is a customer IT admin, not your engineer.

Social login is one integration per provider. Enterprise SSO is one integration per customer. That is why the second half of this guide centers on organizations, not only users.

How do you set up AuthKit in a Remix app?

You install the SDK, set four environment variables, register three redirect settings in the WorkOS dashboard, turn on Remix's single fetch, and add a callback route and a root loader. Together they handle sign-in once and session refresh on every request.

Two flows in a Remix app using WorkOS AuthKit. Sign-in, once per session: the browser requests your login route, which calls getSignInUrl and redirects to AuthKit; the user signs in on AuthKit hosted pages; AuthKit returns the user to your callback route, where authLoader creates the encrypted wos-session cookie. Every request after that: the browser sends the session cookie, the root loader runs authkitLoader to read and refresh the session, then route loaders use authkitLoader and actions use withAuth.
How the pieces fit together in a Remix app.

Before you start, you need:

  • A WorkOS account with your API key and client ID from the dashboard.
  • A Remix v2 app on version 2.16 or later, which is the range the SDK lists as its peer dependency.

!!Want to skip the manual setup? The WorkOS AI Installer & CLI detects your framework, installs the SDK, configures your dashboard, and writes the integration code, all with a single command: npx workos@latest integrate!!

Set up manually

If you ran the CLI, you can skip to the next section. Otherwise, these are the steps to follow.

!!Prefer to start from a working app? The remix-authkit-example repository on GitHub is a sample Remix app that uses AuthKit. It has a sign-in route, a callback route, and an account page that requires a signed-in user. Clone it, copy .env.example to .env, add your WorkOS client ID, API key, redirect URI, and cookie password, and run npm run dev.!!

Step 1: Install the SDK

  
npm install @workos-inc/authkit-remix
  

The package depends on @workos-inc/node, so you do not install that separately.

Step 2: Set your environment variables

  
# .env
WORKOS_API_KEY='sk_test_...'
WORKOS_CLIENT_ID='client_...'
WORKOS_REDIRECT_URI='http://localhost:5173/callback'
WORKOS_COOKIE_PASSWORD='<at least 32 characters>'
  

The cookie password encrypts the session cookie. Generate one with openssl rand -base64 24, which produces 32 characters. The redirect URI uses port 5173 because that is the Vite dev server default, which is what Remix uses; change it if your app runs on another port. All four variables are required.

Step 3: Configure redirects in the dashboard

In the WorkOS dashboard, open Applications, select your app, and go to the Redirects tab. Set three things:

  • Redirect URI: http://localhost:5173/callback. It must match WORKOS_REDIRECT_URI.
  • Initiate login URI: http://localhost:5173/login. Sign-in does not always start in your app, for example when a user follows an invitation or password reset email. AuthKit sends those requests to this route, which has to start an AuthKit sign-in and not render your own form.
  • Sign-out URI: a page to land on after sign-out. Without one, users see an error when they sign out.

Step 4: Turn on single fetch

The SDK builds its loader responses with Remix's data helper, which Remix supports through the single fetch future flag. The sample app enables it, and so does this guide. Add the flag in vite.config.ts, and the type declaration so loader types match:

  
import { vitePlugin as remix } from '@remix-run/dev';
import { defineConfig } from 'vite';

// Types for loaders and actions that return data().
declare module '@remix-run/node' {
  interface Future {
    v3_singleFetch: true;
  }
}

export default defineConfig({
  plugins: [
    remix({
      future: {
        v3_singleFetch: true,
      },
    }),
  ],
});
  

Step 5: Add the routes

Remix v2 builds routes from file names in app/routes. A dot in a file name becomes a slash in the URL, and _index is the route for /. These are the files this guide creates:

File in app/routes URL Purpose
_index.tsx / Home page with sign-in and sign-out
login.ts, sign-up.ts /login, /sign-up Redirect to AuthKit
callback.ts /callback Receives the user back from AuthKit
dashboard.tsx, projects.tsx /dashboard, /projects Protected pages
onboarding.tsx, switch-organization.ts /onboarding, /switch-organization Organization setup and switching
settings.sso.tsx /settings/sso Enterprise SSO and directory setup
api.reports.ts, webhooks.workos.ts /api/reports, /webhooks/workos Resource routes

Step 6: Add the callback route

  
import { authLoader } from '@workos-inc/authkit-remix';

export const loader = authLoader({ returnPathname: '/dashboard' });
  

authLoader exchanges the authorization code for a session and redirects to returnPathname. If you need to persist OAuth tokens after sign-in, authLoader also accepts an onSuccess option.

Step 7: Run authkitLoader in the root loader

  
import type { LoaderFunctionArgs } from '@remix-run/node';
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from '@remix-run/react';
import { authkitLoader } from '@workos-inc/authkit-remix';

// Runs on every request. It reads the session cookie and refreshes it when needed.
export const loader = (args: LoaderFunctionArgs) => authkitLoader(args);

export default function App() {
  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <Meta />
        <Links />
      </head>
      <body>
        <Outlet />
        <ScrollRestoration />
        <Scripts />
      </body>
    </html>
  );
}
  

The SDK docs call for authkitLoader in a root or parent loader, because that is where session refresh and cookie updates happen. The rest of root.tsx stays as it is.

Import server-only SDK code (@workos-inc/authkit-remix) from route modules and from files named *.server.ts, so it stays out of your client bundle.

How do sign-in, sign-up, and sessions work in a Remix app?

Sign-in and sign-up run on AuthKit's hosted pages, so you do not build forms for passwords, email verification, MFA, or social login. Your app sends the user to AuthKit, handles the callback you registered, and reads the session in loaders.

How do you add the sign-in and sign-up routes?

Ask the SDK for the AuthKit URL in a loader and redirect to it. The login route also serves as your Initiate login URI.

  
import { redirect, type LoaderFunctionArgs } from '@remix-run/node';
import { getSignInUrl } from '@workos-inc/authkit-remix';

export async function loader({ request }: LoaderFunctionArgs) {
  const returnTo = new URL(request.url).searchParams.get('returnTo');

  // Only accept paths inside your own app.
  const returnPathname = returnTo?.startsWith('/') && !returnTo.startsWith('//') ? returnTo : undefined;

  return redirect(await getSignInUrl(returnPathname));
}
  
  
import { redirect, type LoaderFunctionArgs } from '@remix-run/node';
import { getSignUpUrl } from '@workos-inc/authkit-remix';

export async function loader({ request }: LoaderFunctionArgs) {
  const returnTo = new URL(request.url).searchParams.get('returnTo');

  // Only accept paths inside your own app.
  const returnPathname = returnTo?.startsWith('/') && !returnTo.startsWith('//') ? returnTo : undefined;

  return redirect(await getSignUpUrl(returnPathname));
}
  

getSignInUrl and getSignUpUrl return the AuthKit URL as a string, and they take an optional path to send the user to after sign-in. The routes read that path from a returnTo query parameter, and accept only paths inside your own app, so a crafted link cannot send users to another site.

How do you read the current user in a loader?

Call authkitLoader in the route's loader and read the result with useLoaderData. It returns the user from the session, or null if nobody is signed in.

  
import type { ActionFunctionArgs, LoaderFunctionArgs } from '@remix-run/node';
import { Form, Link, useLoaderData } from '@remix-run/react';
import { authkitLoader, signOut } from '@workos-inc/authkit-remix';

export const loader = (args: LoaderFunctionArgs) => authkitLoader(args);

export async function action({ request }: ActionFunctionArgs) {
  return signOut(request);
}

export default function Home() {
  const { user } = useLoaderData<typeof loader>();

  if (!user) {
    return (
      <main>
        <h1>Welcome</h1>
        <Link to="/login">Sign in</Link> | <Link to="/sign-up">Sign up</Link>
      </main>
    );
  }

  return (
    <main>
      <h1>Welcome back{user.firstName ? `, ${user.firstName}` : ''}</h1>
      <Form method="post">
        <button type="submit">Sign out</button>
      </Form>
    </main>
  );
}
  

Besides user, the result includes sessionId, organizationId, role, roles, permissions, entitlements, and impersonator. The access token is not sent to your components by default. If a loader needs it for a server-side API call, use the getAccessToken() function that authkitLoader passes to a custom loader.

How do session refresh and sign-out work?

After the callback, the session lives in an encrypted, HTTP-only cookie named wos-session by default. authkitLoader refreshes the session when needed and sets the updated cookie on the response. The onSessionRefreshError option lets you decide what happens when a refresh fails.

The signOut(request) call in the example above ends the session at WorkOS and redirects the user. By default the destination is the Redirect URI you configured under Redirects in the dashboard. You can pass a returnTo value, as long as it is allowed under logout redirects in the dashboard. See the AuthKit sessions docs for the session model.

How do you protect routes and actions in Remix?

Check the session inside every loader and action that reads or writes data. Loaders use authkitLoader, which can redirect to sign-in. Actions and resource routes use withAuth, which reads the session and lets you decide the response. Nested routes make this per-route checking necessary, since the loaders of all matched routes run in parallel and a parent check does not gate its children.

Helper Use it in Refreshes the session When nobody is signed in
authkitLoader The root loader and each route loader Yes Returns user: null, or redirects to AuthKit with ensureSignedIn: true
withAuth Actions, resource routes, shared helpers No Returns user: null and leaves the response to you

How do you require a signed-in user in a loader?

Pass ensureSignedIn: true. If there is no session, authkitLoader redirects the user to AuthKit.

  
import type { LoaderFunctionArgs } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';
import { authkitLoader } from '@workos-inc/authkit-remix';

export const loader = (args: LoaderFunctionArgs) => authkitLoader(args, { ensureSignedIn: true });

export default function Dashboard() {
  const { user } = useLoaderData<typeof loader>();
  return <h1>Dashboard for {user.email}</h1>;
}
  

With ensureSignedIn, the types guarantee a user, so user.email needs no null check. Put the same call in every route that needs a user, including child routes of a layout.

How do you protect actions and mutations?

An action is a POST request your server accepts directly, so a redirect in a page loader does not protect it. Write one helper that checks the user, the active organization, and a permission, and call it at the top of every action. It uses withAuth, which accepts loader or action arguments.

  
import { data, redirect, type ActionFunctionArgs, type LoaderFunctionArgs } from '@remix-run/node';
import { withAuth } from '@workos-inc/authkit-remix';

/**
 * Use in actions and resource routes: confirms there is a signed-in user,
 * an active organization, and the required permission.
 */
export async function requirePermission(args: LoaderFunctionArgs | ActionFunctionArgs, permission: string) {
  const auth = await withAuth(args);

  if (!auth.user) {
    const returnTo = encodeURIComponent(new URL(args.request.url).pathname);
    throw redirect(`/login?returnTo=${returnTo}`);
  }
  if (!auth.organizationId) throw redirect('/onboarding');
  if (!auth.permissions?.includes(permission)) throw data('Forbidden', { status: 403 });

  return { user: auth.user, organizationId: auth.organizationId };
}
  

withAuth does not refresh the session, so treat a missing user as "sign in again". The helper redirects to the login route and returns the user to the page afterward. Then use it in the action:

  
import { data, redirect, type ActionFunctionArgs, type LoaderFunctionArgs } from '@remix-run/node';
import { Form, useLoaderData } from '@remix-run/react';
import { authkitLoader } from '@workos-inc/authkit-remix';
import { db } from '../db.server';
import { requirePermission } from '../lib/auth.server';

export async function action(args: ActionFunctionArgs) {
  const { organizationId } = await requirePermission(args, 'projects:write');

  const form = await args.request.formData();
  const projectId = String(form.get('projectId'));
  const name = String(form.get('name'));

  // Look the record up inside the active organization, never by the client's ID alone.
  const project = await db.project.findFirst({ where: { id: projectId, organizationId } });
  if (!project) throw data('Not found', { status: 404 });

  await db.project.update({ where: { id: project.id }, data: { name } });
  return { ok: true };
}
  

Two details matter here. The permission check and the lookup both rely on organizationId from the session, and the project is fetched within that organization, so a user cannot rename another tenant's project by guessing an ID. And the helper throws Remix responses, so do not wrap it in a try/catch that swallows the redirect or the 403.

How do you protect a JSON resource route?

A resource route that returns JSON should answer with a status code, not a redirect:

  
import { data, type LoaderFunctionArgs } from '@remix-run/node';
import { withAuth } from '@workos-inc/authkit-remix';

export async function loader(args: LoaderFunctionArgs) {
  const { user, organizationId } = await withAuth(args);

  // A JSON endpoint should answer with a status code, not a redirect to a sign-in page.
  if (!user || !organizationId) {
    return data({ error: 'Not authenticated' }, { status: 401 });
  }

  // Query reports where organizationId matches the session's organization.
  return data({ organizationId, reports: [] as unknown[] });
}
  

How do organizations and roles work in a multi-tenant Remix app?

In WorkOS, an organization represents one of your customers. A user joins an organization through a membership, and each membership has a role. The session carries the active organization, so authkitLoader and withAuth return organizationId, role, and permissions for the organization the user is acting in. A user can be an admin in one organization and a viewer in another.

Data model for a multi-tenant B2B app on WorkOS AuthKit. A user joins an organization through a membership that carries a role and permissions. Each customer is one organization. An organization can have a verified domain, an SSO connection using SAML or OIDC, and a directory connected through SCIM, which provisions memberships.
One organization per customer. SSO, directory sync, and roles all attach to the same object.

How do you create an organization?

Create the organization and the first membership, then switch the session to it. The role slug has to exist under Roles in the WorkOS dashboard; the roles and permissions docs explain how roles and permissions are modeled.

  
import { redirect, type ActionFunctionArgs } from '@remix-run/node';
import { Form } from '@remix-run/react';
import { getWorkOS, switchToOrganization, withAuth } from '@workos-inc/authkit-remix';

export async function action(args: ActionFunctionArgs) {
  const { user } = await withAuth(args);
  if (!user) throw redirect('/login');

  const form = await args.request.formData();
  const workos = getWorkOS();

  const organization = await workos.organizations.createOrganization({
    name: String(form.get('name')),
  });

  // The role slug must exist under Roles in the WorkOS dashboard.
  await workos.userManagement.createOrganizationMembership({
    organizationId: organization.id,
    userId: user.id,
    roleSlug: 'admin',
  });

  // Save organization.id on your own tenant record here.

  // Make the new organization the active one in the session, then go to the dashboard.
  return switchToOrganization(args.request, organization.id, { returnTo: '/dashboard' });
}

export default function Onboarding() {
  return (
    <Form method="post">
      <input name="name" placeholder="Company name" required />
      <button type="submit">Create organization</button>
    </Form>
  );
}
  

getWorkOS() returns the SDK's configured WorkOS client, and switchToOrganization refreshes the session for the new organization and redirects to returnTo, which should be a path inside your own app. New users who sign up without an invitation have a valid session but no active organization, so send them to a step like this one before they see a dashboard with no tenant behind it.

How do you check organization membership and role in a loader?

Read organizationId and permissions from the session. Permissions arrive with it, so a check is an array lookup and not a database query.

  
import { data, redirect, type ActionFunctionArgs, type LoaderFunctionArgs } from '@remix-run/node';
import { Form, useLoaderData } from '@remix-run/react';
import { authkitLoader } from '@workos-inc/authkit-remix';
import { db } from '../db.server';
import { requirePermission } from '../lib/auth.server';

export async function loader(args: LoaderFunctionArgs) {
  return authkitLoader(
    args,
    async ({ auth }) => {
      // No active organization yet: send the user to create or join one.
      if (!auth.organizationId) throw redirect('/onboarding');

      // Scope every query to the organization in the session.
      const projects = await db.project.findMany({ where: { organizationId: auth.organizationId } });

      return {
        projects: projects as { id: string; name: string }[],
        canWrite: auth.permissions.includes('projects:write'),
      };
    },
    { ensureSignedIn: true },
  );
}
  

Always take organizationId from the session, never from a URL segment or a form field. A user can edit those; the session cannot be edited. Hiding the rename form with canWrite is a usability choice only. The action still performs its own check.

How do users switch organizations?

Call switchToOrganization from an action with the target organization ID. The session comes back with that organization's role and permissions.

  
import type { ActionFunctionArgs } from '@remix-run/node';
import { switchToOrganization } from '@workos-inc/authkit-remix';

export async function action({ request }: ActionFunctionArgs) {
  const form = await request.formData();
  return switchToOrganization(request, String(form.get('organizationId')), { returnTo: '/dashboard' });
}
  

When you pass returnTo, a successful switch redirects there. Without it, the function returns data with success and the updated auth fields, and on failure it returns success: false with an error message, for example when the user is not authorized for that organization. Role and permission changes made in WorkOS reach the session when its access token next refreshes.

How do you add enterprise SSO (SAML or OIDC) for a customer?

You enable Single Sign-On in the WorkOS dashboard, create an organization with a verified domain, and give the customer's IT admin a link to configure their own identity provider. The SAML and OIDC handshakes stay outside your codebase, and your login and callback routes do not change. This is the step where B2B apps differ from consumer apps.

How does AuthKit route users to the right identity provider?

Turn on Single Sign-On under Authentication in the dashboard. From then on, AuthKit checks whether a user is eligible for SSO when they sign in or sign up, and routes them based on organizations that have verified their email domain:

  • If an organization's domain policy requires SSO for that domain, the user goes straight to that organization's identity provider.
  • If the user is an active member of exactly one organization that verified the domain, that organization's policy applies.
  • Otherwise, when shared-domain discovery is enabled, AuthKit offers the eligible SSO connections on the domain and asks the user to choose when there is more than one.

After an SSO sign-in, authkitLoader returns the same kind of session as any other method, with organizationId set to the organization the user signed in through. The organization policies docs describe the options, and the AuthKit SSO docs cover the flow.

How do you test SSO before you have a customer?

Every staging environment includes a test organization with an active SSO connection backed by a Test Identity Provider. Open the Test SSO page in the dashboard and run its scenarios, including sign-in that starts from the identity provider, which never starts at your /login route.

Screenshot of the Test SSO dashboard page.

How do you onboard a customer's IT admin?

Create an organization for the customer with the domain they will verify, and keep organization.id in your own database:

  
import { getWorkOS } from '@workos-inc/authkit-remix';
import { DomainDataState } from '@workos-inc/node';

export async function provisionCustomer(name: string, domain: string) {
  const organization = await getWorkOS().organizations.createOrganization({
    name,
    domainData: [{ domain, state: DomainDataState.Pending }],
  });

  // Persist organization.id on your own tenant record.
  return organization.id;
}
  

Then give the IT admin a way into the Admin Portal, a hosted setup flow with instructions for each identity provider. Generate the link on demand from an action that only authorized admins can reach, and redirect immediately, because portal links expire after five minutes.

  
import { redirect, type ActionFunctionArgs, type LoaderFunctionArgs } from '@remix-run/node';
import { Form } from '@remix-run/react';
import { getWorkOS } from '@workos-inc/authkit-remix';
import { GeneratePortalLinkIntent } from '@workos-inc/node';
import { requirePermission } from '../lib/auth.server';

export async function loader(args: LoaderFunctionArgs) {
  await requirePermission(args, 'org:sso:configure');
  return null;
}

export async function action(args: ActionFunctionArgs) {
  const { organizationId } = await requirePermission(args, 'org:sso:configure');
  const form = await args.request.formData();

  const intent = form.get('intent') === 'dsync' ? GeneratePortalLinkIntent.DSync : GeneratePortalLinkIntent.SSO;

  const { link } = await getWorkOS().portal.generateLink({ organization: organizationId, intent });
  return redirect(link);
}

export default function SsoSettings() {
  return (
    <Form method="post">
      <button type="submit" name="intent" value="sso">Set up single sign-on</button>
      <button type="submit" name="intent" value="dsync">Set up directory sync</button>
    </Form>
  );
}
  

The org:sso:configure permission is one you define under Roles in the dashboard. The admin follows the guided steps, pastes in their identity provider's metadata, and the connection goes live. Unless an organization allows any domain, SSO needs a verified domain to activate, and the portal also supports a domain_verification intent for the DNS record.

How do you add SCIM directory sync?

SSO controls how people sign in. Directory sync controls who has an account at all: when someone joins the customer's company they get access, and when they leave, they lose it, without a support ticket. WorkOS connects to a customer's directory (Okta, Microsoft Entra ID, Google Workspace, and others) over SCIM and normalizes the providers into one set of directories, groups, users, and events. See the Directory Sync docs for the full model.

What does directory sync add on top of SSO?

With AuthKit there is one distinction to know. Directory Sync alone does not create AuthKit users. Directory provisioning builds on it, and does:

Behavior Directory Sync alone With directory provisioning
AuthKit user created per directory user No Yes
Organization membership created No Yes, marked as directory-managed
Group-to-role mapping Applied to the directory user Applied to the membership and the access token claims
User removed in the directory Directory user updated Membership deactivated

The directory provisioning docs list each action and the events it emits.

How do you turn on directory sync for a customer?

Use the same route as for SSO. The second button in the example above submits intent=dsync, which maps to GeneratePortalLinkIntent.DSync, and the IT admin follows the guided setup for their directory provider. Deleting a directory in the Admin Portal does not automatically revoke access for users it provisioned, so remove access first if that is what the customer intends.

How do you handle provisioning events with webhooks?

WorkOS sends webhooks as directories change. Create a resource route, verify the signature, and update your own records. Keep your database keyed to WorkOS IDs, because email addresses change.

  
import { data, type ActionFunctionArgs } from '@remix-run/node';
import { getWorkOS } from '@workos-inc/authkit-remix';

export async function action({ request }: ActionFunctionArgs) {
  const payload = await request.json();
  const sigHeader = request.headers.get('workos-signature') ?? '';

  let event;
  try {
    event = await getWorkOS().webhooks.constructEvent({
      payload,
      sigHeader,
      secret: process.env.WORKOS_WEBHOOK_SECRET!,
    });
  } catch {
    return data({ error: 'Invalid signature' }, { status: 400 });
  }

  switch (event.event) {
    case 'organization_membership.updated':
      // With directory provisioning, a deprovisioned user's membership becomes inactive.
      break;
    case 'dsync.user.updated':
      // Most directory providers soft-delete: the user arrives here with state 'inactive'.
      break;
    case 'dsync.user.deleted':
      // A hard delete in the directory. Remove the user from your own records.
      break;
  }

  return data({ received: true });
}
  

Register the endpoint under Webhooks in the dashboard and store the signing secret as WORKOS_WEBHOOK_SECRET. WorkOS calls this route without a session, so do not call authkitLoader or requirePermission in it. During a directory's first sync you receive events for every existing user, so make the handler safe to run more than once for the same user.

How does AuthKit differ from consumer-focused auth providers?

Consumer-focused providers are designed around the individual user: sign-up, sign-in, social login, passwordless, and MFA. If that is all your app needs, the first half of this guide is similar in shape to what any of them requires. The differences show up once you sell to organizations. Some providers in this category also offer organizations and enterprise SSO, and the details change over time, so check each vendor's current documentation and pricing. The table lists the questions that separate the options, and how AuthKit answers each one.

Concern In AuthKit What to check with any provider
Tenant model Organizations with memberships and per-organization roles. The session carries the active organization, role, and permissions. Does the session carry an organization and role, or do you map them yourself?
Enterprise SSO SAML and OIDC through the same sign-in flow, routed by verified domain. Is SSO part of the same integration or a separate product?
Customer IT setup A hosted Admin Portal link, generated per organization, with setup guides per identity provider. Can a customer's IT admin self-serve, or does your team handle each setup?
Provisioning SCIM through Directory Sync, with directory provisioning into organization memberships. Are deprovisioned users' memberships and sessions handled automatically?
Framework SDK A Remix SDK with loader helpers, and a separate SDK for React Router. Does the SDK read sessions in loaders and actions, or only in client components?
Pricing unit AuthKit is free up to 1 million monthly active users. Enterprise SSO connections are priced per connection. What counts as a billable unit, and when do SSO and SCIM add cost?

Current prices are on the WorkOS pricing page. The trade-off is scope: AuthKit puts the organization at the center of the model from the start, which is more structure than a single-tenant consumer app needs.

Common mistakes to avoid

  • Relying on a parent loader. Loaders for all matched routes run in parallel, so a layout check does not protect its children. Check in every loader and action.
  • Protecting the page but not the action. A redirect in a loader does nothing for a direct POST. Call a permission helper at the top of each action.
  • Reading the tenant from the URL or a form field. Take organizationId from the session and scope every query to it.
  • Skipping single fetch. The SDK builds its loader responses with Remix's data helper, which Remix supports through the single fetch flag. Turn it on in vite.config.ts, as the sample app does.
  • Trusting returnTo from the URL. Accept only paths that start with a single /, so a crafted link cannot send users to another site.
  • Wrapping redirects in try/catch. Loader helpers and your own checks redirect by throwing, and a catch block swallows the response.
  • Skipping the Initiate login URI or Sign-out URI. Invitation and password reset links need the first, and users see an error on sign-out without the second.
  • Putting the webhook route behind an auth check. WorkOS calls it without a session.
  • Identifying a customer by email domain. Enterprises have contractors and guests with other domains. Use the organization ID from the session.
  • Assuming deleting a directory removes access. Users a directory provisioned keep their accounts and sessions until you remove them.

Frequently asked questions

What are the best authentication providers for a Remix app?

The right choice depends on whether you sell to individuals or to organizations. Self-managed libraries give you full control and leave you to build sessions, MFA, and any enterprise features yourself. Hosted consumer-focused providers cover sign-in, social login, and MFA for individual users. B2B-focused platforms such as WorkOS AuthKit add organizations, enterprise SSO, and SCIM to that base. Whichever you pick, check that it reads the session in loaders and actions and has an SDK for Remix. Top 5 authentication solutions for secure Remix apps in 2026 compares several options.

How do I add SSO to a Remix app?

Install @workos-inc/authkit-remix, set up the callback route and root loader, and enable Single Sign-On in the WorkOS dashboard. Create an organization for the customer with their email domain, then send their IT admin to the Admin Portal with a link generated by getWorkOS().portal.generateLink and the SSO intent. The admin configures their SAML or OIDC identity provider there, and AuthKit then routes that customer's users to it at sign-in. You can verify the flow first with the Test Identity Provider in your staging environment.

Does this work with React Router v7?

Not with this package. This guide is for Remix v2 and @workos-inc/authkit-remix. React Router v7 and v8 apps use @workos-inc/authkit-react-router, which has similar helpers with some different signatures. The structure here carries over: check the session in every loader and action, scope data to the organization in the session, and set up SSO and SCIM per customer. See the React Router version of this guide for the exact code.

Is Remix the same as React Router v7?

Not exactly. Remix v2 is built on React Router, and React Router describes v7 as the next major version after Remix v2, with framework mode carrying over loaders, actions, and nested routes. React Router v8 was announced on June 17, 2026, and Remix v2 reached end of life with it. Remix 3 is a separate framework. React Router's upgrade guide covers moving a Remix v2 app, and after the move you switch from @workos-inc/authkit-remix to @workos-inc/authkit-react-router.

Which AuthKit package should I use, authkit-remix or authkit-react-router?

Use @workos-inc/authkit-remix for Remix v2 apps that import from @remix-run/* packages. Use @workos-inc/authkit-react-router for apps on React Router v7 or v8. Both export helpers such as authkitLoader, authLoader, withAuth, and signOut, but their signatures are not identical, so follow the docs for the package you install.

How do I protect routes in Remix?

Call authkitLoader(args, { ensureSignedIn: true }) in each loader that requires a user, and run authkitLoader in your root loader so sessions refresh. Then check the session again inside each action and resource route with withAuth, scoping queries to the organizationId from the session.

How do I check a user's role or organization in a Remix loader?

Read organizationId, role, and permissions from the object that authkitLoader or withAuth returns. Permissions come from the session, so checking one is an array lookup, for example auth.permissions.includes('projects:write').

How do I add multi-tenancy and roles to a Remix app?

Model each customer as a WorkOS organization, add users through memberships with a role, and read the active organization from the session. Use switchToOrganization for users who belong to more than one organization. See the roles and permissions docs.

How do I add SCIM user provisioning to a Remix app?

Have the customer's IT admin connect their directory through the Admin Portal with the directory sync intent. With directory provisioning enabled, directory users become AuthKit users and organization memberships, and removing someone in the directory deactivates their organization membership. Add a webhook route if your own database needs to react to those changes.

Can I add SSO to an app that already has its own login?

Yes. WorkOS also offers a standalone SSO API that handles only the identity provider handshake and returns a profile you map onto your existing user records, so your current login keeps working alongside it. The same idea is covered for Node in How to add enterprise SSO to an Express.js API.

Which identity providers are supported?

Any provider that speaks SAML or OIDC. WorkOS publishes setup guides for many of them, including Okta, Microsoft Entra ID, and Google Workspace, plus generic SAML and OIDC connectors. See the integrations list.

How much does it cost?

AuthKit is free up to 1 million monthly active users. Enterprise SSO connections are priced per connection, and staging environments are free to use. See the pricing page for current numbers.

Next steps

Start with npx workos@latest integrate or the manual steps above, and keep the AuthKit Remix SDK reference open for every helper and option. Once SSO and directory sync are live, enterprise buyers tend to ask for the rest of the checklist, and it hangs off the same organization object: Role-Based Access Control, Audit Logs, and the Admin Portal so customer IT admins manage their own connections.

Related posts

Sources