Laravel Sanctum with JavaScript

Laravel Sanctum is a package for Laravel that provides a lightweight authentication system for single page applications (SPAs), mobile applications, and simple token-based APIs. It allows for the generation of API tokens that can be used to authenticate requests to your Laravel application without the need for a traditional login process. This can be useful for applications that need to make API requests to your Laravel application from a frontend JavaScript framework like React or Vue.js, or for mobile applications that need to authenticate users without a server-side session.

How to integrate in JavaScript

  1. Install the Laravel Sanctum package by running the following command in your terminal:
composer require laravel/sanctum

2. Publish the package’s configuration and migration files by running the following command:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

3. In your config/auth.php file, make sure the driver option for the api guard is set to sanctum.

4. In your .env file, make sure the SANCTUM_STATEFUL_DOMAINS variable is set to a comma-separated list of domains that should be able to make stateful requests (requests that maintain a user session) to your application.

5. Run the migration to create the necessary database tables by running the following command:

php artisan migrate

6. In your frontend JavaScript code, you can use Laravel Sanctum’s JavaScript library to make API requests to your Laravel application and authenticate them using an API token. To do this, you will need to first install the library using npm or yarn:

npm install @laravel/sanctum

7. In your JavaScript code, you can then use the createToken method to create a new API token for a given user, and the authenticate method to attach the token to subsequent API requests:

import { createToken, authenticate } from '@laravel/sanctum';

// Create a new API token for the authenticated user
createToken('user-id')
    .then(response => {
        // Attach the token to subsequent API requests
        authenticate(response.token);
    });

8. In your Laravel routes, you can use the auth:sanctum middleware to protect routes that require authentication:

Route::get('/profile', function () {
    // Only authenticated users with a valid API token can access this route
})->middleware('auth:sanctum');

You can also check the Laravel Sanctum documentation for more detailed instructions and additional features.

Read More About Laravel Sanctum

Spread the love

Leave a comment

Index