devise-token-auth-client
v0.0.55
Published
TBD
Downloads
9
Readme
Devise Token Auth Client
Installation
yarn add devise-token-auth-client
Usage
This client is based on Axios. See the Axios Docs for basic usage instructions.
The instructions that follow show the usage of this client with Devise Token Auth.
Initialization
The ApiClient
during the setup phase of your app.
import ApiClient from 'devise-token-auth-client';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
async function render = Component => {
// create the client instance
const client = new ApiClient({
baseUrl: 'https://my-api.com'
});
// wait for the client to initialize before use. this will ensure that the
// user session is available for the initial render.
await client.isInitialized;
ReactDOM.render(
<Component client={client} />,
document.getElementById('app')
);
}
render(App);
Usage
Client Instance Methods
emailSignUp
Create a new user account.
When email confirmation is not enabled, this will also authenticate the new user.
emailSignIn
Authenticate an existing user.
oAuthSignIn
Sign in using a 3rd party OAuth provider (i.e. Github, Facebook, etc.). This method will open a popup window that allows the user to authenticate using the 3rd party service. Once the 3rd party authentication is complete, the user will be signed in to our own API and a session will be created in the browser. A new user will be created if no user exists matching the ID and provider of the 3rd party account.
signOut
Clear the current user's session and user state. This method attempts to sign out with the API, but the browser session and state is always cleared, even in the case of API failure.
passwordResetRequest
Sends an email to a user that has forgotten their password. The email will contain a link that allows them to reset their password.
Dispatch Actions
When configured to work with a dispatch
action, the following actions will be
dispatched at the given times.
Advanced Configuration
Redux
To sync with a redux store, simply pass the dispatch
and getState
methods
to the initializer.
import { createStore } from 'redux';
import ApiClient from 'devise-token-auth-client';
import reducers from './reducers';
// ...
const store = createStore(reducers);
const client = new ApiClient({
baseUrl: 'https://my-api.com',
dispatch: store.dispatch,
getState: store.getState
});
Server Side Rendering
The goal of SSR is to pre-render the initial page load of a single-page app (SPA). This is helpful to search engine crawlers that can't parse SPAs, and in some cases it offers better performance and a better user experience.
Devise Token Client supports server-side rendering (SSR). But SSR does complicate the setup. We will need to pass additional configuration params to the initializer on both the server and the client.
SSR Step 1: Initialize on the server
The server needs the following additional params for SSR:
| param | type | description |
|===|===|===|
| location
| (string) | The url for the initial render |
| redirect
| (function) | A function used by the server to redirect to a new page |
| requestCookies
| (object) | An object representation of the cookies contained in the initial request |
| setResponseCookie
| (function) | A method used to set response cookies on the server |
| clearResponseCookie
| (function) | A method used to clear a response cookie on the server |
SSR Server Config Example
This example uses Express. This example is also not sufficient to set up an actual SSR app - it only calls out the steps necessary for authentication. See [here] for a complete, working setup.
import Express from 'express';
import cookieParser from 'cookie-parser';
import { renderToStaticMarkup } from 'react-dom/server';
import { StaticRouter } from 'react-router';
import createStore from './create-store';
import ApiClient from 'devise-token-auth-client';
import HTML from './html';
import App from './app';
// init the app
const app = new Express();
// this middleware will convert the cookie string into an object
app.use(cookieParser());
app.use(async (req, res) => {
// if this is the result of an OAuth redirect, don't render anything
if (req.query.blank) {
return res.send(`<!doctype html>\nAUTHENTICATING...`);
}
const store = createStore();
const client = new ApiClient({
baseUrl: 'https://my-api.com/api',
dispatch: store.dispatch,
getState: store.getState
// SSR-specific params
requestCookies: req.cookies,
setResponseCookie: (key, val) => res.cookie(key, val),
clearResponseCookie: key => res.clearCookie(key),
redirect: url => { context.url = url },
});
// wait until auth session has loaded before rendering the page
await client.isInitialized;
// do an initial render to check for redirects
const { state: serverState, html: content } = await renderToString(
<Provider store={store} key="provider">
<StaticRouter location={req.originalUrl} context={context}>
<App />
</StaticRouter>
</Provider>,
);
// if the redirect was called anywhere in the initial render, actually
// perform the redirect here
if (context.url) {
return res.redirect(context.url);
}
// serve the rendered content to the browser
return res.send(`<!doctype html>\n${html}`);
});
SSR Step 2: Initialize on the client
The client needs the following additional params for SSR:
| param | type | description |
|===|===|===|
| location
| (string) | The url for the initial render |
| redirect
| (function) | A function used by the browser to redirect to a new page |
SSR Client Config Example
import { createStore } from 'redux';
import ApiClient from 'devise-token-auth-client';
import reducers from './reducers';
// ...
const store = createStore(reducers);
const client = new ApiClient({
baseUrl: 'https://my-api.com/api',
dispatch: store.dispatch,
getState: store.getState
});