Skip to content

React Router 7

Quick guide to integrate Vla with React Router 7.

View Example App

Terminal window
npm install vla

Create app/data/kernel.ts:

import { Kernel } from 'vla'
export const kernel = new Kernel()

Use React Router’s middleware function to set up Vla:

app/routes/home.tsx
import { Vla } from 'vla'
import { kernel } from '../data/kernel'
import type { Route } from './+types/home'
const vlaMiddleware: Route.MiddlewareFunction = async (args, next) => {
return Vla.withKernel(kernel.scoped(), next)
}
export const middleware: Route.MiddlewareFunction[] = [vlaMiddleware]
export async function loader() {
const user = await GetUser.invoke('123')
return { user }
}

This creates a scoped kernel for each request.

app/data/users.actions.ts
import { Vla } from 'vla'
class GetUser extends Vla.Action {
async handle(id: string) {
// Your logic here
return { id, name: 'User' }
}
}
// app/routes/users.$id.tsx
export async function loader({ params }: Route.LoaderArgs) {
const user = await GetUser.invoke(params.id)
return { user }
}
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData()
// Handle action
}

To access the request object, create a context:

app/data/context.ts
import { Vla } from 'vla'
export const AppContext = Vla.createContext<{
request: Request
}>()

Update your middleware:

import { Vla } from 'vla'
import { kernel } from '../data/kernel'
import { AppContext } from '../data/context'
import type { Route } from './+types/home'
const vlaMiddleware: Route.MiddlewareFunction = async ({ request }, next) => {
return Vla.withKernel(
kernel.scoped().context(AppContext, { request }),
next
)
}
export const middleware: Route.MiddlewareFunction[] = [vlaMiddleware]

Use in your classes:

class GetCurrentUser extends Vla.Action {
ctx = this.inject(AppContext)
async handle() {
const url = new URL(this.ctx.request.url)
// Use request data
}
}

You’re ready to use Vla in your React Router app. Check out the guides to learn how to structure your code with Actions, Services, and Repos.