User Authentication and Authorization in Payload CMS

This topic covers how to set up and integrate user authentication in a React or Next.js application using Payload CMS. It also includes managing user roles and permissions.

React Example: Login Form Integration

import React, { useState } from 'react';
import axios from 'axios';


const LoginForm = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);


  const handleLogin = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('https://your-payload-cms.com/api/users/login', {
        email,
        password,
      });
      localStorage.setItem('token', response.data.token);
      alert('Login successful!');
    } catch (err) {
      setError('Invalid credentials');
    }
  };


  return (
    <form onSubmit={handleLogin}>
      <input 
        type="email" 
        placeholder="Email" 
        value={email} 
        onChange={(e) => setEmail(e.target.value)} 
      />
      <input 
        type="password" 
        placeholder="Password" 
        value={password} 
        onChange={(e) => setPassword(e.target.value)} 
      />
      {error && <p>{error}</p>}
      <button type="submit">Login</button>
    </form>
  );
};


export default LoginForm;


Leave a comment

Your email address will not be published. Required fields are marked *