Skip to main content

API Reference

Server Methods

These are library methods that can only be called from Next.js server components and server actions. These methods have access to all the data related to the user's account, authentication state and subscription.

ReflowAuth constructor

Follow the getting starter guide on how to initialize and obtain an instance of this class.

import "server-only";
import { ReflowAuth } from "@reflowhq/auth-next";

export default function getAuth(): ReflowAuth {
return new ReflowAuth({
projectID: 123456,
secret: "REPLACE_ME_WITH_A_32_CHAR_SECRET",
});
}

The constructor supports the following options. The first two are required and must always be provided.

ParameterRequiredTypeDefault ValueDescription
projectIDyesnumber-The ID of your Reflow project. You can find it in the Reflow dashboard settings page.
secretyesstring-A 32 character unique string. It is used to encrypt the session cookie where the auth data is stored. Ideally you should keep this in an .env file that is not committed in your repo.
cookieNamenostring"session"The name of the session cookie stored in the browser with the http-only flag. By default the name is "session".
cookieMaxAgenonumber-The lifetime of the session in seconds. By default it is cleared when the browser window is closed.
beforeSigninnofunction-Async callback function which is called before a successful login with the user object as a parameter (example). Useful for performing an action before every login. Return true from the function to allow the login to proceed, and false to prevent it.
testModenobooleanfalseIndicates whether the library should use Reflow's test mode. Useful for testing in development.

isSignedIn

async isSignedIn(): Promise<boolean>

Returns a boolean indicating whether the user is signed in or not.

import getAuth from "@/auth";

export default async function Page() {
const auth = getAuth();
const status = await auth.isSignedIn();
return <p>User is {status ? "signed in" : "not signed in"}!<p>;
}

isSubscribed

async isSubscribed(): Promise<boolean>

Returns a boolean indicating whether the user has an active subscription.

import getAuth from "@/auth";

export default async function Page() {
const auth = getAuth();
const status = await auth.isSubscribed();
return <p>User is {status ? "subscribed" : "not subscribed"}!<p>;
}

user

async user(): Promise<User | null>

Returns a user object with account info.

import getAuth from "@/auth";

export default async function Page() {
const auth = getAuth();
const user = await auth.user();
return <pre>{user}</pre>;
}

Will return an object of type User

interface User {
object: "user";
id: number;
name: string;
email: string;
photo: string;
provider: string;
meta: Record<string, any>;
created: number;
livemode?: boolean;
}
PropertyTypeDescription
objectstringAlways equal to "user"
idnumberThe id of the user
namestringThe name of the user
emailstringThe user's email address. Note that some social networks don't provide this (Twitter/X), give the user the option to not share it (Facebook) or replace it with a relay (Apple).
photostringURL pointing to a user photo. If the login provider doesn't support it, a placeholder image is shown instead.
providerstringThe id of provider, for example "google", "facebook", "twitter", "apple"
metaobjectAn object of key-value pairs. You can set these with the updateUser method. They can be used to store user preferences like choice of light or dark mode and other small pieces of data. Defaults to {}
creatednumberThe timestamp of the account creation, for example 1702053000755.
livemodebooleanIndicates whether this user was created in Live or Test mode.

Here is an example object

{
"success": true,
"user": {
"object": "user",
"id": 123456789,
"name": "John Smith",
"email": "user@example.com",
"photo": "https://cdn.reflowhq.com/media/123456789/profiles/abc123456789.jpeg",
"provider": "google",
"meta": {
"darkMode": true
},
"created_at": 1702053000755
}
}

subscription

async subscription(): Promise<Subscription | null>

Returns the user's current subscription and plan info for the signed-in user.

import getAuth from "@/auth";

export default async function Page() {
const auth = getAuth();
const sub = await auth.subscription();
return <pre>{sub}</pre>;
}

Returns an object of the following types

interface Subscription {
object: "subscription";
id: number;
status: string;
last_billing: null | number;
next_billing: null | number;
cancel_at: null | number;
plan: Plan;
price: Price;
}

interface CurrencyCode {
code: string;
name: string;
zero_decimal: boolean;
}

interface Plan {
object: "plan";
id: number;
name: string;
description: string;
parameters: Record<string, any>;
}

interface Price {
object: "plan_price";
id: number;
price: number;
price_formatted: string;
currency: CurrencyCode;
billing_period: string;
is_taxed: boolean;
tax_behavior: string;
is_archived: boolean;
created: number;
}

Here is an example JSON object

{
"object": "subscription",
"id": 12345,
"status": "active",
"last_billing": null,
"next_billing": 1634024400,
"cancel_at": null,
"plan": {
"object": "plan",
"id": 54321,
"name": "Premium Plan",
"description": "Access to all premium features",
"parameters": {},
"trial_days": 7,
"subscription_setup_fee": null
"is_archived": false,
"created": 1630876800
},
"price": {
"object": "plan_price",
"id": 98765,
"price": 9.99,
"price_formatted": "$9.99",
"currency": {
"code": "USD",
"name": "US Dollar",
"zero_decimal": false
},
"billing_period": "monthly",
"is_taxed": true,
"tax_behavior": "inclusive",
"is_archived": false,
"created": 1630876800
}
}

updateUser

async updateUser(options: UpdateUserOptions): Promise<{success: boolean; pendingEmailVerification?:boolean}>

This method updates the user information stored at Reflow. You can use it to update the name, email, photo and meta data of the user. The options argument follows the following type definition.

interface UpdateUserOptions {
name?: string;
email?: string;
photo?: Blob;
meta?: Record<string, any>;
}
PropertyTypeDescription
namestringNew name for the user. By default the name is retrieved from the social sign in provider at the time of registration.
emailstringThe user's new email address.
photoBlobThis is an object of the Blob class that is available in browsers and Node.js. Many web APIs return this type including canvas and file inputs.
metaobjectObject of key-value pairs which you wish to merge with the existing meta data of the user.

All fields are optional, but you need to provide at least one.

The method returns an object with properties success and pendingEmailVerification. The latter is set to true when you've changed the email address of the user and they need to click a validation link that's been delivered by Reflow to their new email address. When true, show a notification or some other message.

// Note, works only in server actions and route handlers, not in server components.

const update = {
email: "new-email@example.com",
name: "John Sample",
meta: { sidebarStatus: "collapsed" },
photo: new Blob(),
};

const result = await auth.updateUser(update);
console.log(result);
/*
{
success: true,
pendingEmailVerification: true,
}
*/

IMPORTANT. Note that this method modifies the auth session cookie. This means that it can't be used in server components, since they are rendered after cookies are delivered to the browser. You can only call this method in server actions and route handlers.

deleteUser

async deleteUser(): Promise<{success: boolean}>

This method deletes the current user's account and information stored at Reflow. You can use it implement account deletion functionality in your apps. The method won't allow the user to delete their account if they have an active subscription.

The method returns an object with a boolean success property.

// Note, works only in server actions and route handlers, not in server components.
const result = await auth.deleteUser();
console.log(result);
/*
{
success: true
}
*/

IMPORTANT. Note that this method modifies the auth session cookie. This means that it can't be used in server components, since they are rendered after cookies are delivered to the browser. You can only call this method in server actions and route handlers.

isNew

async isNew(): Promise<boolean>

Returns whether the user is newly registered. You can use this status to determine whether to display getting started guides or walkthroughs. The isNew flag is stored in a cookie which expires at the end of the browser session.

import getAuth from "@/auth";

export default async function Page() {
const auth = getAuth();
const status = await auth.isNew();
return <p>User is {status ? "new" : "old"}!<p>;
}

setIsNew

async setIsNew(): Promise<void>

Sets the isNew flag for the current session. Will create a cookie which expires at the end of the browser session.

IMPORTANT. Note that this method modifies a cookie. This means that it can't be used in server components, since they are rendered after cookies are delivered to the browser. You can only call this method in server actions and route handlers.

await auth.setIsNew();

clearIsNew

async clearIsNew(): Promise<void>

Clear the isNew cookie forcefully.

IMPORTANT. Note that this method modifies a cookie. This means that it can't be used in server components, since they are rendered after cookies are delivered to the browser. You can only call this method in server actions and route handlers.

await auth.clearIsNew();

set

async set(key: string, value: any): Promise<void>
async set({ key: string; value: any }[]): Promise<void>

This method sets arbitrary data in the session which can be retrieved later with get. You can use this method as an alternative to other session libraries.

The method comes in two forms, you can pass the key and value as arguments, or you can pass an array of keys and values to set a large number of items simultaneously.

Note that the session data is stored in the same encrypted cookie that the reflow user data is stored. As a good practice, try to keep the data you store in the session small, since cookies are sent on every HTTP request.

See an example in the Cookie Session Management guide.

get

async get(key: string, def: any = null): Promise<any>

Returns a value from the session, which you've previously set with set.

has

async has(key: string): Promise<boolean>

Checks whether a key exists in the session.

forget

async forget(key: string): Promise<void>

Removes a value from the session.

clear

async clear(): Promise<void>

Clears all data in the session. The user is signed out of their account and all data you've set is lost.

clearSystem

async clearSystem(): Promise<void>

Removes only system values that hold sign-in info. The customer will be signed out but any custom session data you've added will be retained.

all

async all(): Promise<Record<string, any>>

Returns all data in the session as a JS object of key-value pairs.

refresh

async refresh(): Promise<AuthRefreshChange | null>
export interface AuthRefreshChange {
signout: boolean;
user: boolean;
subscription: boolean;
}

Pull the latest user account info from Reflow and update the data stored in the cookie.

IMPORTANT. Note that this method modifies the auth session cookie. This means that it can't be used in server components, since they are rendered after cookies are delivered to the browser. You can only call this method in server actions and route handlers.

await auth.refresh();

lastRefresh

async lastRefresh(): Promise<number | null>

Returns the timestamp of the last sync with the Reflow backend. Returns either a date timestamp like 1702053000755 or null if not sync has been made yet. Note that the Reflow library handles its own sync so normally you don't need to force it to refresh.

import getAuth from "@/auth";

export default async function Page() {
const auth = getAuth();
const ts = await auth.lastRefresh();
return <p>Last sync with Reflow was at {ts}<p>;
}

handleRequest

async handleRequest(request: Request): Promise<Response>

Handler for the backend API with which the front end JS methods communicate. You can see it used in the Getting Started guide section for app/auth/route.ts.

Client Methods

The following methods are available in client components only. They can be imported from @reflowhq/auth-next/client.

signIn

async function signIn(options?: {authEndpoint?: string; onSignin?: Function; onSubscribe?: Function; onError?: Function; step?: "login" | "register"; subscribeTo?: number;})

Triggers the sign in flow and displays a window with sign in methods.

Accepts an options object with the following properties, all of which are optional.

PropertyTypeDescription
authEndpointstringThe path on your website where Next.js serves the auth route handler you created in the setup. By default, this is set to "/auth". If you use a non-standard route handler name or location you will need to change this.
onSigninFunctionCallback function which is called when the user signs in successfully.
onSubscribeFunctionCallback function which is called when the user subscribes successfully.
onSuccessFunctionDeprecated, please use the onSignin and onSubscribe callbacks instead.
onErrorFunctionCallback function which is called when an error occurs during sign in.
stepstringIf you use the Username and Password auth provider, this indicates whether to display the login or register screens. This is only for convenience, users can navigate between them from the links in the window regardless.
subscribeTonumberYou can provide a priceID if you wish the user to be presented with a subscription screen immediately after signing in. It is used internally by the createSubscription method if the user is not logged in when it's called.
subscribeWithstringThe payment provider that should be used for handling the subscription, either 'stripe' or 'paddle'.

signOut

async function signOut(options?: {authEndpoint?: string; onSuccess?: Function; onError?: Function;})

Signs out the currently logged in user.

Accepts an options object with the following properties, all of which are optional.

PropertyTypeDescription
authEndpointstringThe path on your website where Next.js serves the auth route handler you created in the setup. By default, this is set to "/auth". If you use a non-standard route handler name or location you will need to change this.
onSuccessFunctionCallback function which is called when the user signs out successfully.
onErrorFunctionCallback function which is called when an error occurs during sign out.

createSubscription

async function createSubscription(options?: {options: {priceID: number;authEndpoint?: string;paymentProvider?: onSignin?: Function; onSubscribe?: Function;onError?: Function;}})

Displays a payment window to the currently signed in user, where they can sign up for the subscription plan at the price given in the priceID option.

The priceID option is required, the rest are optional.

PropertyTypeDescription
priceIDnumberThe id of a plan price object. You can obtain this from the Reflow control panel or the API.
authEndpointstringThe path on your website where Next.js serves the auth route handler you created in the setup. By default, this is set to "/auth". If you use a non-standard route handler name or location you will need to change this.
paymentProviderstringThe payment provider that should be used for handling the subscription, either 'stripe' or 'paddle'.
onSigninFunctionCallback function which is called when the user signs in successfully.
onSubscribeFunctionCallback function which is called when the user subscribes successfully.
onSuccessFunctionDeprecated, please use the onSignin and onSubscribe callbacks instead.
onErrorFunctionCallback function which is called when an error occurs during subscription creation.

modifySubscription

async function modifySubscription(options?: { authEndpoint?: string;onSuccess?: Function;onError?: Function; })

Opens a window which lets the user change their payment method and billing info, or switch to a different plan if available.

PropertyTypeRequiredDescription
authEndpointstringOptionalThe path on your website where Next.js serves the auth route handler you created in the setup. By default, this is set to "/auth". If you use a non-standard route handler name or location you will need to change this.
onSuccessFunctionOptionalCallback function which is called after the subscription changes are applied and the management dialog is closed.
onErrorFunctionOptionalCallback function which is called when an error occurs during subscription management.

isSignedIn

async function isSignedIn(options?: { authEndpoint?: string })

Returns a boolean indicating whether the user is currently signed in or not. This is the client counterpart of the isSignedIn() method available on the auth instance on the server. This method invokes a fetch request to the backend every time it is called, so it's better to rely on the auth version instead of this one whenever possible.

PropertyTypeRequiredDescription
authEndpointstringOptionalThe path on your website where Next.js serves the auth route handler you created in the setup. By default, this is set to "/auth". If you use a non-standard route handler name or location you will need to change this.

useSessionSync React Hook

This is a React hook which lets you listen to events originating from other browser tabs. Use this hook to listen for signin, signout and subscribe events. Alternatively, pass an onChange callback which accepts an event type parameter (can be one of "signin", "signout" and "subscribe").

See how we use it to build a toolbar notifying the user if they have signed in another browser tab in our example application.

Signature

function useSessionSync(options: {
authEndpoint?: string;
onChange?: (event: "signin" | "signout" | "subscribe") => void;
onSignin?: Function;
onSignout?: Function;
onSubscribe?: Function;
});
PropertyTypeDescription
authEndpointstringThe path on your website where Next.js serves the auth route handler you created in the setup. By default, this is set to "/auth". If you use a non-standard route handler name or location you will need to change this.
onSigninFunctionCallback function which is called when the user signs into their account from another tab.
onSingoutFunctionCallback function which is called when the user signs out from another tab.
onSubscribeFunctionCallback function which is called when the user subscribes to your app on another tab, browser or device.
onChangeFunctionInstead of passing separate onSignin, onSignout and onSubscribe callback, you can pass this one and determine the event from the function argument.