Magic link authentication provides a simple and secure way for users to log in without needing a password. In this guide, we’ll set up magic link authentication using React for the frontend, Flask for the backend, and Authsignal for handling authentication.
Prerequisites
- Node.js and npm installed
- Python and pip installed
- Basic knowledge of React and Flask
Step 1: Setting Up the Backend with Flask
- Create a new Flask project:
mkdir flask-auth
cd flask-auth
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
pip install Flask
- Install additional dependencies:
pip install authsignal flask-cors
- Create the Flask app (
app.py
):
from flask import Flask, request, jsonify
from flask_cors import CORS
from authsignal import Authsignal
app = Flask(__name__)
CORS(app)
# Initialize Authsignal
authsignal = Authsignal(api_key="YOUR_AUTHSIGNAL_API_KEY")
@app.route('/send-magic-link', methods=['POST'])
def send_magic_link():
data = request.json
email = data.get('email')
result = authsignal.magic_link.send(email)
return jsonify(result)
@app.route('/verify-magic-link', methods=['POST'])
def verify_magic_link():
data = request.json
token = data.get('token')
result = authsignal.magic_link.verify(token)
return jsonify(result)
if __name__ == '__main__':
app.run(debug=True)
- Run the Flask app:
python app.py
Step 2: Setting Up the Frontend with React
- Create a new React project:
npx create-react-app react-auth
cd react-auth
- Install Axios for API requests:
npm install axios
- Create the authentication components:
- Login Component (
Login.js
):
import React, { useState } from 'react';
import axios from 'axios';
const Login = () => {
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
const sendMagicLink = async () => {
try {
const response = await axios.post('http://localhost:5000/send-magic-link', { email });
setMessage(response.data.message);
} catch (error) {
setMessage('Error sending magic link');
}
};
return (
<div>
<h2>Login</h2>
<input
type="email"
placeholder="Enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button onClick={sendMagicLink}>Send Magic Link</button>
<p>{message}</p>
</div>
);
};
export default Login;
- Verify Component (
Verify.js
):
import React, { useState } from 'react';
import axios from 'axios';
import { useSearchParams } from 'react-router-dom';
const Verify = () => {
const [searchParams] = useSearchParams();
const token = searchParams.get('token');
const [message, setMessage] = useState('');
const verifyMagicLink = async () => {
try {
const response = await axios.post('http://localhost:5000/verify-magic-link', { token });
setMessage(response.data.message);
} catch (error) {
setMessage('Error verifying magic link');
}
};
React.useEffect(() => {
if (token) {
verifyMagicLink();
}
}, [token]);
return (
<div>
<h2>Verify</h2>
<p>{message}</p>
</div>
);
};
export default Verify;
- Update the main app component (
App.js
):
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Login from './Login';
import Verify from './Verify';
function App() {
return (
<Router>
<div className="App">
<Routes>
<Route path="/" element={<Login />} />
<Route path="/verify" element={<Verify />} />
</Routes>
</div>
</Router>
);
}
export default App;
- Run the React app:
npm start
Step 3: Testing the Magic Link Flow
- Open the React app in your browser (usually at
http://localhost:3000
). - Enter an email address and click “Send Magic Link”.
- Check the email for the magic link and click it. It should redirect to the verification route (
http://localhost:3000/verify?token=YOUR_TOKEN
). - The
Verify
component will handle the verification and display the result.
Conclusion
You have now set up a simple magic link authentication system using React, Flask, and Authsignal. This setup can be expanded and customized to fit more complex authentication workflows and user management systems.