Skip to content

Instantly share code, notes, and snippets.

@dillingham
Last active June 28, 2022 21:12
Show Gist options
  • Save dillingham/8f6c371958bbd4640d9241256fc734c7 to your computer and use it in GitHub Desktop.
Save dillingham/8f6c371958bbd4640d9241256fc734c7 to your computer and use it in GitHub Desktop.

An Laravel + Inertia like experience using NextJS

Using the Laravel Breeze + Next example here

Anything returned from Laravel backend becomes a prop in NextJS page.

Works as long as the NextJS page path matches the backend api routes.

Route::get('users/{user}', [UserController::class, 'show']);
public function show(User $user)
{
    return [
        'user' => $user,
    ];
}

/pages/users/[user].js

// this line exports getServerSideProps which does the "binding"

export { getServerSideProps } from '@/lib/bindings'

export default ({ user }) => {
  return (<p>{ user.name }</p>)
})

/libs/bindings.js

import axios from "@/lib/axios"

export async function getServerSideProps(context) {

    let endpoint = __filename
        .split('.next/server/pages/')[1]
        .replace('.js', '')
    
    const variables = [...endpoint.matchAll(/\[(\w+)\]/g)];

    variables.forEach(variable => {
        endpoint = endpoint.replace(
            variable[0], // [user]
            context.params[variable[1]] // user
        )
    })

    let output = {}

    await axios.get(`/${endpoint}`, {
        headers: {
            'Cookie': context.req.headers.cookie,
        }
    }).then((response) => {
        output['props'] = response.data
    })

    return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment