It seems like you're looking for a more seamless way to ensure that the timezone offset is set without having to rely on a dedicated page that forces a reload. One approach to handle this is to use a JavaScript function to check and set the timezone offset before making any Inertia requests. Here's how you can do it:
- Update your
bootstrap.jsto include a function that sets the timezone offset header if it's not already set:
function setTimezoneOffsetHeader() {
const timezoneOffset = new Date().getTimezoneOffset() * -1;
window.axios.defaults.headers.common['X-Timezone-Offset'] = timezoneOffset;
}
// Call this function before your app initializes or before making any Inertia requests
setTimezoneOffsetHeader();
- Modify your middleware to check for the timezone offset and set it in the session if it's not already there:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Inertia\Inertia;
class EnsureTimezoneOffset
{
public function handle(Request $request, Closure $next)
{
if (App::environment('testing')) {
return $next($request);
}
$timezoneOffset = $request->header('X-Timezone-Offset');
if ($timezoneOffset === null) {
// Instead of rendering a page, you can abort with a specific status code
// or handle this case in a way that's more suitable for your application.
abort(400, 'Timezone offset header is missing.');
}
if ($timezoneOffset !== session('timezoneOffset')) {
session(['timezoneOffset' => $timezoneOffset]);
}
return $next($request);
}
}
- There's no need for a dedicated reload page. Instead, handle the missing timezone offset header on the client side by checking the response status code and setting the header accordingly.
For example, you could use an Axios response interceptor to catch the specific status code you used to abort the request (e.g., 400) and then set the header:
axios.interceptors.response.use(response => {
return response;
}, error => {
if (error.response && error.response.status === 400) {
setTimezoneOffsetHeader();
// Optionally, retry the last request with the new header
return axios.request(error.config);
}
return Promise.reject(error);
});
This way, if the timezone offset header is missing, the interceptor will catch the error, set the header, and optionally retry the request. This eliminates the need for a separate page and provides a smoother user experience.