Hello! Today I'm going to detail how to easily implement user authentication in your react projects. I'll keep it as brief as possible.
1) In your project directory, install the easybase-react library with npm i easybase-react
.
2) Wrap your application's root component in the EasybaseProvider
like so:
import { EasybaseProvider, useEasybase } from "easybase-react";
function App() {
return (
<EasybaseProvider>
<ProjectUser />
</EasybaseProvider>
)
}
3) Create a project at Easybase and download your ebconfig.js
token. Pass this to the EasybaseProvider
like so:
import { EasybaseProvider, useEasybase } from "easybase-react";
import ebconfig from "ebconfig.js";
function App() {
return (
<EasybaseProvider ebconfig={ebconfig}>
<ProjectUser />
</EasybaseProvider>
)
}
4) Create a component that uses isUserSignedIn()
for conditional rendering based on the user's authentication status.
function ProjectUser() {
const { isUserSignedIn, signIn, signUp } = useEasybase();
if (isUserSignedIn()) {
return (
<div>
<h2>You're signed in!</h2>
</div>
)
} else {
return (
<div>
<h2>User not authenticated :( </h2>
</div>
)
}
}
5) Implement workflow for users to sign in and sign up via the signUp()
and signIn()
functions from the useEasybase
hook. Your component could work as follows:
const [usernameValue, setUsernameValue] = useState("");
const [passwordValue, setPasswordValue] = useState("");
if (isUserSignedIn()) {
return (
<div>
<h2>You're signed in!</h2>
<button onClick={_ => getUserAttributes().then(console.log)}>
Clicking me only works if your authenticated!
</button>
<FrameRenderer />
</div>
)
} else {
return (
<div style={ { display: "flex", flexDirection: "column" } }>
<h4>Username</h4>
<input value={usernameValue} onChange={e => setUsernameValue(e.target.value)} />
<h4>Password</h4>
<input type="password" value={passwordValue} onChange={e => setPasswordValue(e.target.value)} />
<button onClick={_ => signIn(usernameValue, passwordValue)}>
Sign In
</button>
<button onClick={_ => signUp(usernameValue, passwordValue)}>
Sign Up
</button>
</div>
)
}
A few notes on this implementation:
- You can use
onSignIn()
to run a callback function whenever a user signs in (manually from thesignIn()
function or automatically from temporary tokens stored on a user's device). - Creating an easybase account is free.
- Authenticated users can also make valid calls to your tables in Easybase. Here's some info on stateful database array w/ Easybase and React.
Thanks for reading!
Discussion
Hi, do you reckon it would be a bit more clear if you were to include that this is specifically for Easybase in the title? I can only imagine someone less experienced seeing this for the first time and and probably including this in their project when it might not be the best solution for them.
Good point! I'll change it now
It seems pretty cool.
good post. I like it for real.
Thanks!