Use LoggedIn user ID as default when recordId is not present

Hi,

I was looking for a way to user the Logged in user’s ID as a default record on a details page and was able to do it with a simple custom code, so I figured I would share it in case anyone else is looking for a way to do this.

In our system we have a “Person” page with details of a “Person” record on our Airtable database. Some people are users, others are not. Throughout the application, we have links to the “Person” page and typically they will link to a specific record. For instance, on another page we have a list of people where the user can find a specific record and click on it to go to the details page.

We wanted, however to allow for the users to link to their “Person” page directly from the header menu, but Softr doesn’t offer any way to pass the logged in user’s record ID as a URL parameter to the “Person” page.

As with any record detail blocks in Softr, if you try to load the page without a “recordId” url parameter, you will end up seeing a useless random record (I am still trying to think of a useful use-case for this Softr behavior).

Our solution was to add a simple script to the “Person” page:

<script>
    // Get the current URL
    const url = new URL(window.location.href);
    
    // Define the parameter to check and its default value
    const paramName = 'recordId';
    const userId = window.logged_in_user?.airtable_record_id || null;
    // Get the URL parameters
    let params = url.searchParams;
    
    // Unless there's no logged_in_user or url already specifies a record ID
    if (userId && !params.has(paramName)) {
        console.log('loaded without recordId, will default to logged in user')
        params.set(paramName, userId); // use userId as default recordId
        // Recreates URL and reloads the page
        window.location.href = url.protocol + '//' + url.host + url.pathname + '?' + params.toString();
    }
</script>

Hope this helps!

Cheers