Connect Session
An NPM package to simplify OAuth with Reapit Connect
We are aware that managing OAuth flows can be tricky, especially redirecting, keeping sessions refreshed and cached. To make this process easier, we have built the Connect Session module for any JavaScript app.
To get started run yarn add @reapit/connect-session
Then follow the steps for either browsers, React or NodeJS below.

Basic Browser Usage

The module is intended to be browser framework agnostic although we ship a React Hook for React users (see below).
For all users, in a file at the root of the source of your project, first instantiate and export the ReapitConnectBrowserSession class.
The constructor accepts 5 parameters, of which two are optional, see comments below. The production connectUserPoolId is eu-west-2_eQ7dreNzJ .
1
import { ReapitConnectBrowserSession } from '@reapit/connect-session'
2
3
// You should instantiate the class once only as a singleton as the module manages it's own state
4
export const reapitConnectBrowserSession = new ReapitConnectBrowserSession({
5
// The client id of your application, obtained from Reapit Developer Portal
6
connectClientId: 'SOME_CLIENT_ID',
7
// The url to the Reapit Connect instance. While in beta this is the below URL but will need to be context aware in full prod/
8
connectOAuthUrl: 'https://connect.reapit.cloud',
9
// OAuth UserPoolId - refer to the foundations documentation to obtain this for the correct environment
10
connectUserPoolId: 'SOME_USER_POOL_ID',
11
// The relative path you want to re-direct in your application after a successful login. You will have supplied this when you registered your app.
12
// Defaults to '' or the root of your project if not supplied
13
connectLoginRedirectPath: '/some-redirect-path',
14
// The relative path you want to re-direct in your application after a successful logout. You will have supplied this when you registered your app.
15
// Defaults to '/login' if not supplied
16
connectLogoutRedirectPath: '/some-login-path',
17
// The time in ms before your session times out when a user is inactive.
18
// Defaults to 10800000 - 3hrs
19
connectApplicationTimeout: 10800000
20
})
Copied!
The instantiated class can then be used in your code. It exports the following methods:
1
import { reapitConnectBrowserSession } from './path-to-your-module'
2
3
// The definition of the reapitConnectBrowserSession
4
interface ReapitConnectSession {
5
// The accessToken is the `Bearer <<token>>` you need to authenticate against the platform API.
6
accessToken: string
7
// Refresh token is provided as a convenience - in practice the module handle's refreshing and caching of your session out the box
8
refreshToken: string
9
// Id token is provided as a convenience - the parsed output is below in the loginIdentity object below
10
idToken: string
11
loginIdentity: {
12
email: string
13
name: string
14
developerId: string | null
15
clientId: string | null
16
adminId: string | null
17
userCode: string | null
18
groups: string[]
19
orgName: string | null
20
orgId: string | null
21
offGroupIds: string | null
22
offGrouping: boolean
23
offGroupName: string | null
24
officeId: string | null
25
}
26
}
27
28
// Returns a promise containing your reapitSession object as per the interface above
29
reapitConnectBrowserSession.connectSession().then((reapitSession: ReapitConnectSession) => reapitSession)
30
31
// Handles redirect to authorization endpoint - in most cases, I don't need to call in my app as handled by the module
32
// but made public in case I want to override the redirect URI I specified in the constructor
33
reapitConnectBrowserSession.connectAuthorizeRedirect(redirectUri: string)
34
35
// Handles redirect to logout - defaults to constructor login uri but I can override if I like.
36
reapitConnectBrowserSession.connectLogoutRedirect(redirectUri: string)
37
38
// Handles redirect to login - defaults to constructor redirect uri but I can override if I like.
39
reapitConnectBrowserSession.connectLoginRedirect(redirectUri: string)
40
41
// A convenience getter to check if my app has been loaded inside RPS / Desktop / Agency Cloud
42
reapitConnectBrowserSession.connectIsDesktop
43
44
// A convenience getter to check if my app has a valid session
45
reapitConnectBrowserSession.connectHasSession
46
47
// Allows the current session in memory to be cleared programatically.
48
// Useful if you want to trigger a refresh of your session from a refresh token in
49
// session storage.
50
reapitConnectBrowserSession.connectClearSession
Copied!

React Usage

In addition to the basic browser API, we export a React Hook to use in your React Components.
To leverage the Hook, first instantiate the class as per above. Then, around the Routes you wish to protect with Reapit Connect authentication, simply return when the session is not present as below:
1
// import the instantiated class, the hook and the provider
2
import { useReapitConnect } from '@reapit/connect-session'
3
import { reapitConnectBrowserSession } from './connect-session'
4
5
export const PrivateRouteWrapper: React.FC = ({ children }) => {
6
// Call the hook to retun a session object
7
const { connectSession } = useReapitConnect(reapitConnectBrowserSession)
8
9
// The session object implements the same interface as the browser class with the exception that the connectSession promise is handled wrapped in a useEffect hook and so is just an objecy or null. Here I return null from the component while I am fetching a session
10
if (!connectSession) {
11
return null
12
}
13
14
// I now have a session I can render my App
15
return (
16
<AppNavContainer>
17
<Menu />
18
</AppNavContainer>
19
)
20
}
Copied!
Then in my React child components, I have access to the session values and methods eg:
1
import { useReapitConnect } from '@reapit/connect-session'
2
import { reapitConnectBrowserSession } from './connect-session'
3
4
export const SomeComponent: React.FC = () => {
5
const { connectSession, connectLogoutRedirect } = useReapitConnect(reapitConnectBrowserSession)
6
const handleLogout = () => connectLogoutRedirect('/custom-login-path') // Optional path param
7
8
return (
9
<CustomFetchComponent connectSession={connectSession}>
10
<Button onClick={handleLogout}>I am a logout button!</Button>
11
</CustomFetchComponent>
12
)
13
}
Copied!

Sign In With Reapit Button

Perhaps the simplest way to authenticate on the client side is to embed the "Sign In With Reapit Button" on your page. This is not exported from the NPM package as it is distributed via a CDN however, you can see full documentation here.

Node Usage

For server side usage, we also export a Node module with a stripped down API that simply returns a promise from a connectAccessToken method. For a basic and slightly contrived example, see the simple Express app below:
1
import 'isomorphic-fetch'
2
import express, { Router, Request, Response } from 'express'
3
import bodyParser from 'body-parser'
4
import cors from 'cors'
5
import { ReapitConnectServerSession, ReapitConnectServerSessionInitializers } from '@reapit/connect-session'
6
import config from './config.json'
7
8
const router = Router()
9
10
const { connectClientId, connectClientSecret, connectOAuthUrl, connectUserPoolId } = config as ReapitConnectServerSessionInitializers
11
12
const reapitConnectSession = new ReapitConnectServerSession({
13
connectClientId,
14
connectClientSecret,
15
connectOAuthUrl,
16
})
17
18
router.get('/get-access-token', async (req: Request, res: Response) => {
19
const accessToken = await reapitConnectSession.connectAccessToken()
20
// Do some stuff with my access token here, will just return it to the user as an example
21
res.status(200)
22
res.send(accessToken)
23
res.end()
24
})
25
26
const app = express()
27
28
app.use(cors())
29
app.use(bodyParser.urlencoded({ extended: true }))
30
app.use(bodyParser.json())
31
app.use('/', router)
32
33
app.listen('3000', () => {
34
console.log('App is listening on 3000')
35
})
Copied!
As per the browser usage, you will need to instantiate the class with your initialisers, in this case connectClientId, connectOAuthUrl (in the same way as the browser module), but with the addition of the connectClientSecret you obtain from your app listing page.
The module will fetch and refresh your session as the token expires, caching it in session storage to minimise calls to Reapit Connect token endpoint. After closing a tab, the session cache is not persisted.
Last modified 1mo ago