Passwords can be forgotten, and forcing users to reset via email every time is annoying. With magic links, we can provide a secure and seamless password backup system. In this tutorial, I’ll show how to implement it in Node.js using the auth-verify library.
Install dependecies
npm install auth-verify express
- auth-verify: To handle magic links
- express: To create server routes.
Setup auth-verify
Initialize in your server.js:
const express = require('express')
const app = express()
const AuthVerify = require('auth-verify')
const auth = new AuthVerify({
mlSecret: 'super_secret_key', // making secret for magic links
mlExpiry: '5m', // magic links expiration time
appUrl: 'http://localhost:3000', // URL of running app
storeTokens: 'memory' // Storing magic links on 'memory' or 'redis'
})
// Configuring magic link sender
auth.magic.sender({
service: 'gmail',
sender: 'yourapp@gmail.com',
pass: 'your_gmail_app_password'
})
Create Magic Link Endpoint
When a user forgets their password, we send a magic link to their email.
app.post('/send-magic-link', async (req, res)=> {
const { email } = req.body
try {
const result = await auth.magic.send(email, {
subject: 'Your Reset password Link ✨',
html: `<p>Click below to sign in:</p>
<a href="{{link}}">Login Now</a>` // {{link}} automatically changes to link like localhost:3000/auth/verify?token=GENERATED_TOKEN
})
res.json({ success: true, message: 'Magic link sent!', result })
}catch(err){
console.error(err)
res.status(500).json({ success: false, message: 'Failed to send magic link' })
}
})
Create Verification end point
When user clicks the link that sent to his/her email token will be verified
app.get('/auth/verify', async (req, res) => {
const { token } = req.query; // getting token by link
try {
await auth.magic.verify(token)
res.send(`
<form method="POST" action="/reset-password">
<input name="newpassword" type="password">
<button type="submit">Set new password</button>
</form>
`)
} catch (err) {
res.status(400).json({ success: false, message: err.message })
}
})
Set the new password
At this endpoint new password will be set by user
app.post('/reset-password', (req, res)=> {
const { newpassword } = req.body // getting new password of user
// And new password will be set in here...
})
Conclusion:
With magic links, users can reset their passwords without remembering old ones. Using auth-verify makes this setup secure and easy. You now have a simple Node.js password backup system that’s user-friendly and secure.
Top comments (0)