Skip to content

sergiodxa/remix-auth

Repository files navigation

Remix Auth

Simple Authentication forRemix

Features

  • FullServer-SideAuthentication
  • CompleteTypeScriptSupport
  • Strategy-based Authentication
  • Easily handlesuccess and failure
  • Implementcustomstrategies
  • Supports persistentsessions

Overview

Remix Auth is a complete open-source authentication solution for Remix.run applications.

Heavily inspired byPassport.js,but completely rewrote it from scratch to work on top of theWeb Fetch API.Remix Auth can be dropped in to any Remix-based application with minimal setup.

As with Passport.js, it uses the strategy pattern to support the different authentication flows. Each strategy is published individually as a separate npm package.

Installation

To use it, install it from npm (or yarn):

npm install remix-auth

Also, install one of the strategies. A list of strategies is available in theCommunity Strategies discussion.

Usage

Remix Auth needs a session storage object to store the user session. It can be any object that implements theSessionStorage interface from Remix.

In this example I'm using thecreateCookieSessionStoragefunction.

// app/services/session.server.ts
import{createCookieSessionStorage}from"@remix-run/node";

// export the whole sessionStorage object
exportletsessionStorage=createCookieSessionStorage({
cookie:{
name:"_session",// use any name you want here
sameSite:"lax",// this helps with CSRF
path:"/",// remember to add this so the cookie will work in all routes
httpOnly:true,// for security reasons, make this cookie http only
secrets:["s3cr3t"],// replace this with an actual secret
secure:process.env.NODE_ENV==="production",// enable this in prod only
},
});

// you can also export the methods individually for your own usage
exportlet{getSession,commitSession,destroySession}=sessionStorage;

Now, create a file for the Remix Auth configuration. Here import theAuthenticatorclass and yoursessionStorageobject.

// app/services/auth.server.ts
import{Authenticator}from"remix-auth";
import{sessionStorage}from"~/services/session.server";

// Create an instance of the authenticator, pass a generic with what
// strategies will return and will store in the session
exportletauthenticator=newAuthenticator<User>(sessionStorage);

TheUsertype is whatever you will store in the session storage to identify the authenticated user. It can be the complete user data or a string with a token. It is completely configurable.

After that, register the strategies. In this example, we will use theFormStrategyto check the documentation of the strategy you want to use to see any configuration you may need.

import{FormStrategy}from"remix-auth-form";

// Tell the Authenticator to use the form strategy
authenticator.use(
newFormStrategy(async({form})=>{
letemail=form.get("email");
letpassword=form.get("password");
letuser=awaitlogin(email,password);
// the type of this user must match the type you pass to the Authenticator
// the strategy will automatically inherit the type if you instantiate
// directly inside the `use` method
returnuser;
}),
// each strategy has a name and can be changed to use another one
// same strategy multiple times, especially useful for the OAuth2 strategy.
"user-pass"
);

Now that at least one strategy is registered, it is time to set up the routes.

First, create a/loginpage. Here we will render a form to get the email and password of the user and use Remix Auth to authenticate the user.

// app/routes/login.tsx
importtype{ActionFunctionArgs,LoaderFunctionArgs}from"@remix-run/node";
import{Form}from"@remix-run/react";
import{authenticator}from"~/services/auth.server";

// First we create our UI with the form doing a POST and the inputs with the
// names we are going to use in the strategy
exportdefaultfunctionScreen(){
return(
<Formmethod="post">
<inputtype="email"name="email"required/>
<input
type="password"
name="password"
autoComplete="current-password"
required
/>
<button>Sign In</button>
</Form>
);
}

// Second, we need to export an action function, here we will use the
// `authenticator.authenticate method`
exportasyncfunctionaction({request}:ActionFunctionArgs){
// we call the method with the name of the strategy we want to use and the
// request object, optionally we pass an object with the URLs we want the user
// to be redirected to after a success or a failure
returnawaitauthenticator.authenticate("user-pass",request,{
successRedirect:"/dashboard",
failureRedirect:"/login",
});
};

// Finally, we can export a loader function where we check if the user is
// authenticated with `authenticator.isAuthenticated` and redirect to the
// dashboard if it is or return null if it's not
exportasyncfunctionloader({request}:LoaderFunctionArgs){
// If the user is already authenticated redirect to /dashboard directly
returnawaitauthenticator.isAuthenticated(request,{
successRedirect:"/dashboard",
});
};

With this, we have our login page. If we need to get the user data in another route of the application, we can use theauthenticator.isAuthenticatedmethod passing the request this way:

// get the user data or redirect to /login if it failed
letuser=awaitauthenticator.isAuthenticated(request,{
failureRedirect:"/login",
});

// if the user is authenticated, redirect to /dashboard
awaitauthenticator.isAuthenticated(request,{
successRedirect:"/dashboard",
});

// get the user or null, and do different things in your loader/action based on
// the result
letuser=awaitauthenticator.isAuthenticated(request);
if(user){
// here the user is authenticated
}else{
// here the user is not authenticated
}

Once the user is ready to leave the application, we can call thelogoutmethod inside an action.

exportasyncfunctionaction({request}:ActionFunctionArgs){
awaitauthenticator.logout(request,{redirectTo:"/login"});
};

Advanced Usage

Custom redirect URL based on the user

Say we have/dashboardand/onboardingroutes, and after the user authenticates, you need to check some value in their data to know if they are onboarded or not.

If we do not pass thesuccessRedirectoption to theauthenticator.authenticatemethod, it will return the user data.

Note that we will need to store the user data in the session this way. To ensure we use the correct session key, the authenticator has asessionKeyproperty.

exportasyncfunctionaction({request}:ActionFunctionArgs){
letuser=awaitauthenticator.authenticate("user-pass",request,{
failureRedirect:"/login",
});

// manually get the session
letsession=awaitgetSession(request.headers.get("cookie"));
// and store the user data
session.set(authenticator.sessionKey,user);

// commit the session
letheaders=newHeaders({"Set-Cookie":awaitcommitSession(session)});

// and do your validation to know where to redirect the user
if(isOnboarded(user))returnredirect("/dashboard",{headers});
returnredirect("/onboarding",{headers});
};

Changing the session key

If we want to change the session key used by Remix Auth to store the user data, we can customize it when creating theAuthenticatorinstance.

exportletauthenticator=newAuthenticator<AccessToken>(sessionStorage,{
sessionKey:"accessToken",
});

With this, bothauthenticateandisAuthenticatedwill use that key to read or write the user data (in this case, the access token).

If we need to read or write from the session manually, remember always to use theauthenticator.sessionKeyproperty. If we change the key in theAuthenticatorinstance, we will not need to change it in the code.

Reading authentication errors

When the user cannot authenticate, the error will be set in the session using theauthenticator.sessionErrorKeyproperty.

We can customize the name of the key when creating theAuthenticatorinstance.

exportletauthenticator=newAuthenticator<User>(sessionStorage,{
sessionErrorKey:"my-error-key",
});

Furthermore, we can read the error using that key after a failed authentication.

// in the loader of the login route
exportasyncfunctionloader({request}:LoaderFunctionArgs){
awaitauthenticator.isAuthenticated(request,{
successRedirect:"/dashboard",
});
letsession=awaitgetSession(request.headers.get("cookie"));
leterror=session.get(authenticator.sessionErrorKey);
returnjson({error},{
headers:{
'Set-Cookie':awaitcommitSession(session)// You must commit the session whenever you read a flash
}
});
};

Remember always to use theauthenticator.sessionErrorKeyproperty. If we change the key in theAuthenticatorinstance, we will not need to change it in the code.

Errors Handling

By default, any error in the authentication process will throw a Response object. IffailureRedirectis specified, this will always be a redirect response with the error message on thesessionErrorKey.

If afailureRedirectis not defined, Remix Auth will throw a 401 Unauthorized response with a JSON body containing the error message. This way, we can use the CatchBoundary component of the route to render any error message.

If we want to get an error object inside the action instead of throwing a Response, we can configure thethrowOnErroroption totrue.We can do this when instantiating theAuthenticatoror callingauthenticate.

If we do it in theAuthenticator,it will be the default behavior for all theauthenticatecalls.

exportletauthenticator=newAuthenticator<User>(sessionStorage,{
throwOnError:true,
});

Alternatively, we can do it on the action itself.

import{AuthorizationError}from"remix-auth";

exportasyncfunctionaction({request}:ActionFunctionArgs){
try{
returnawaitauthenticator.authenticate("user-pass",request,{
successRedirect:"/dashboard",
throwOnError:true,
});
}catch(error){
// Because redirects work by throwing a Response, you need to check if the
// caught error is a response and return it or throw it again
if(errorinstanceofResponse)returnerror;
if(errorinstanceofAuthorizationError){
// here the error is related to the authentication process
}
// here the error is a generic error that another reason may throw
}
};

If we define bothfailureRedirectandthrowOnError,the redirect will happen instead of throwing an error.