Magic link integration using Lemón’s transactional email API
1. Generate the Magic Link
Use an authentication provider (e.g., Firebase, Auth0, or a custom token generator) to create a time-sensitive link. For simplicity, let’s assume you're using a custom token generator.
Example (Node.js):
const crypto = require("crypto");
// Generate a secure token
const generateMagicLink = (email) => {
const token = crypto.randomBytes(32).toString("hex");
const redirectUri = encodeURIComponent(`https://yourapp.com/verify?token=${token}`);
return { magicLink: redirectUri, token };
};
2. Send the Magic Link via Lemón
Using Lemón’s transactional email API, send the generated link.
Node.js Example:
const axios = require("axios");
// Magic Link Generation
const { magicLink, token } = generateMagicLink("recipient@domain.com");
// Lemón Email API Call
const sendMagicLink = async () => {
const payload = {
fromname: "YourApp",
fromemail: "no-reply@yourapp.com",
to: "recipient@domain.com",
subject: "Your Magic Login Link",
body: `
<html>
<body>
<p>Hello,</p>
<p>Click the link below to log in:</p>
<a href="${magicLink}">Log in</a>
<p>This link will expire in 10 minutes.</p>
</body>
</html>
`
};
try {
const response = await axios.post(
"https://app.xn--lemn-sqa.com/api/transactional/send",
payload,
{
headers: {
"Content-Type": "application/json",
"X-Auth-APIKey": "YOUR_API_KEY"
}
}
);
console.log("Email sent successfully:", response.data);
} catch (error) {
console.error("Error sending email:", error.response?.data || error.message);
}
};
sendMagicLink();
3. Handle the Magic Link on the Backend
When the user clicks the link, validate the token.
Backend Validation Example:
const express = require("express");
const app = express();
const tokenStore = new Map(); // Replace with a database in production
// Simulate storing tokens
tokenStore.set("some-token", { email: "recipient@domain.com", expiresAt: Date.now() + 600000 });
app.get("/verify", (req, res) => {
const token = req.query.token;
if (!tokenStore.has(token)) {
return res.status(400).send("Invalid or expired link.");
}
const { email, expiresAt } = tokenStore.get(token);
if (Date.now() > expiresAt) {
return res.status(400).send("Link has expired.");
}
// Log in the user or start a session
res.send(`Welcome back, ${email}!`);
});
app.listen(3000, () => console.log("Server running on port 3000"));
4. Test the Integration
- Use your app to send a magic link.
- Click the link in the email.
- Verify that the link redirects and authenticates the user properly.