authentication in javascript

There are various ways to implement authentication in JavaScript. One way is to use JSON Web Tokens (JWT) and send them as Authorization header with each subsequent request to the server.

Here is a simple example of how to perform authentication with JWT in JavaScript using Axios library:

index.tsx
import axios from 'axios';

// Helper function to set Authorization header with JWT
const setAuthToken = token => {
  if (token) {
    // Apply authorization token to every request if logged in
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  } else {
    // Delete auth header
    delete axios.defaults.headers.common['Authorization'];
  }
};

// User login function
const loginUser = async (email, password) => {
  try {
    const response = await axios.post('/api/auth', { email, password });
    const { token } = response.data;

    // Store token in local storage
    localStorage.setItem('jwtToken', token);

    // Set token to Auth header
    setAuthToken(token);

    return response.data; // Return user data
  } catch (error) {
    console.error(error.response.data); // Log error response
  }
};

// User logout function
const logoutUser = () => {
  // Remove token from local storage
  localStorage.removeItem('jwtToken');

  // Remove auth header
  setAuthToken(false);
};
1013 chars
40 lines

In this example, loginUser function sends a POST request with user credentials to /api/auth endpoint on the server. If the server validates the user credentials, it sends back a JWT as response, which is stored in local storage and used as authentication token for subsequent requests.

The logoutUser function removes the JWT from local storage and removes it from the Authorization header on subsequent requests.

gistlibby LogSnag