Matterholt
2022-08-20
After getting the signed up with Magic.link and the keys tucked away in the env it is time to start putting the code to work and getting the app. I want to use NEXT.js but the process should be similar across all frameworks. (not evaluated)
Get an image of how the web app is structured. Here is a ruff structure.
So initially we will need an account for Magic link so sign up is fairly simple. All you need is an email account. For this project, I will use “npx create-next-app”, but any other framework should work. and would need to install Magic “npm install —save magic-sdk” which will help handle the “magic” on the client-side. There is a need to handle the server-side so installing “npm install —save @magic-sdk/admin” will help tie everything together
// ./pages/login.js
const handleSubmit = async (event) => {
event.preventDefault();
const body = {
email: event.currentTarget.email.value,
};
///.... more code to follow
};
// ./pages/login.js
const handleSubmit = async (event) => {
event.preventDefault();
const body = {
email: event.currentTarget.email.value,
};
///.... more code to follow
};
// inside the handleSubmit function
try {
const magic = new Magic(process.env.NEXT_PUBLIC_MAGIC_PUB_KEY);
const DID_Token = await magic.auth.loginWithMagicLink({
email: body.email,
});
// inside the handleSubmit function
// inside the try statement
const res = await fetch("/api/login", {
method: "POST",
headers: {
"Content-type": "application/json",
Authorization: "Bearer " + DID_Token,
},
body: JSON.stringify(body),
});
For the front side there is a need to handle error to which are listed below.
try {
await m.auth.loginWithMagicLink({ email: 'hello@example.com', showUI: false });
} catch(err) {
if (err instanceof RPCError) {
switch(err.code) {
case RPCErrorCode.MagicLinkFailedVerification:
case RPCErrorCode.MagicLinkExpired:
case RPCErrorCode.MagicLinkRateLimited:
case RPCErrorCode.UserAlreadyLoggedIn:
// Handle errors accordingly :)
break;
}
}