#Automatically pass updatable parameter to server API on every request

7 messages · Page 1 of 1 (latest)

nova nacelle
#

I'm trying to setup live preview with Craft CMS. To do that I need to receive token as a query perimeter and append it to my GraphQL requests. I have a version working by adding to the context via server middleware. The token causes the returned GraphQL data to be from a draft in the CMS instead of the published version.

I'd like to update this functionality to hot reload the page's data not have to reload the whole page. refreshNuxtData() sounds like exactly what I need. However, I can't figure out how to have my server API get this updated toke passed to it. It doesn't seem like Pinia can be used in a Nuxt server file. parseCookies() doesn't seem to get the updated values of cookies that were set just be refreshNuxtData() is run. Changes to the URL query perimeters with router.replace() also don't seem to be noticed.

What's the best way to run code on every server API call that has access to the requesting page's URL or access to a shared state I can update from other components like App.vue?

The below server middleware code works, but I can't figure out how to make it refreshNuxtData() compatible.

export default defineEventHandler((event) => {
    if (event?.node?.req?.url) {
        // Get params from requesting page's URL
        const hashes = event.node.req.url.slice(event.node.req.url.indexOf('?') + 1).split('&');
        const params = {};
        hashes.map((hash) => {
            const [key, val] = hash.split('=');
            params[key] = decodeURIComponent(val);
        });

        // If there's Craft preview params add Craft's token to the request so it can be passed back to Craft
        // /server/api/craft.js looks for this token
        if ((params['x-craft-preview'] || params['x-craft-live-preview']) && params['token']) {
            event.context.craftPreviewToken = params['token'];
        }
    }
});
#

Automatically pass updatable parameter to server API on every request

chrome vapor
#

Doesn’t Crafts preview feature do a hard reload anyway? How are you circumventing this in the first place?

nova nacelle
chrome vapor
#

Lol. ChatGPT really is outdated.

wary birch
#

since, usually when I asked a question, some guys always sent me answers from there (until then I didn't know he helped with that) and I never thought it was bad