Laravel 419 error using Uppy open source, how to add csrf token to Uppy?

Viewed 1343

Before some of you mark this as duplicate since error 419 using laravel has been answered a million times, this is a bit more complicated and I cant seem to work around it.

I am trying to use Uppy to upload some images however I cant seem to find a way to add the csrf token to Uppy. (https://uppy.io/docs/tus/#headers)

const uppy = Uppy();
uppy.use(Dashboard, { target: '#drag-drop-area', inline: true, height: 450 });
uppy.use(Tus, {
     header: 'X-CSRF-TOKEN'+document.querySelector('[name=csrf-token]').getAttribute('content'),
     endpoint: 'https://mysitev/tus', // use your tus endpoint here
     resume: true,
     autoRetry: true,
     retryDelays: [0, 1000, 3000, 5000]
})

Does anyone has used Uppy in the past and if so how did you include the csrf_token?

Thanks

3 Answers

Try with it:

uppy.use(Uppy.Tus, {
    endpoint: '{{ $endpoint }}',
    headers: {
        'X-CSRF-Token': " {{ csrf_token() }} "
    }
})

If you're using Webpack or have your Uppy configuration bundled with other JavaScript files you can assign your token to a meta tag and use it in JS later

In your blade.php

<meta name="csrf-token" content="{{ csrf_token() }}">

Then in your Uppy.js

.use(Tus, {
endpoint: '/tus', // use your tus endpoint here
retryDelays: [0, 1000, 3000, 5000],
headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}

})

I have not used Uppy, but if your code is in your view file, it means the files which have blade extensions can use blade functions to add a csrf token:

headers: {
        'X-CSRFToken': " {{csrf_token()}} "
    }
Related