Valet

Configuration

Environment variables, client options, and Metro config.

Environment Variables

VariableDescription
VALET_PROJECT_URLFull URL for server communication (e.g., https://fly.valet.host/projects/my-app)
VALET_DEPLOY_KEYDeploy key for authenticated schema and handler pushes

Set these in .env for development or .env.production for production builds. You can also set them as actual environment variables in your shell or CI environment.

.env
VALET_PROJECT_URL=https://fly.valet.host/projects/my-app
VALET_DEPLOY_KEY=your_deploy_key_here

ValetClient Options

ValetClient is the core client that manages the WebSocket connection, subscriptions, and mutations. You rarely construct it directly -- createValetProvider handles this -- but the options are available for advanced use cases.

app.ts
import { ValetClient } from 'valet-dev/react'

const client = new ValetClient({
    url: process.env.VALET_PROJECT_URL!,
    authToken: async () => {
        const session = await getSession()
        return session.token
    },
    authRefreshBuffer: 60000,
    syncEngine: syncEngine,
    mutationLog: mutationLog,
    handlers: handlers,
    onConnectionChange: (state) => {
        console.log('Connection:', state)
    },
    onAuthStateChange: (state, userId, error) => {
        console.log('Auth:', state, userId)
    },
    onError: (error) => {
        console.error('Valet error:', error)
    },
    onProtocolMismatch: (serverVersion, clientVersion) => {
        console.warn('Protocol mismatch:', serverVersion, clientVersion)
    },
})
OptionTypeDescription
urlstringServer URL — accepts both HTTP (https://) and WebSocket (wss://) formats. HTTP URLs are automatically converted to WebSocket URLs. (required)
authTokenstring | () => Promise<string>Static token or async function that returns a token
authRefreshBuffernumberMilliseconds before token expiry to trigger refresh (default: 60000)
syncEngineSyncEngineEnables offline support and local query execution
mutationLogMutationLogEnables offline mutation persistence for deterministic replay
handlersHandlerRegistryHandler registry for local query and mutation execution
onConnectionChange(state: ConnectionState) => voidCalled when connection state changes (disconnected, connecting, connected, reconnecting)
onAuthStateChange(state: AuthState, userId?: string, error?: AuthError) => voidCalled when auth state changes (pending, authenticated, unauthenticated, error)
onError(error: Error) => voidCalled on unrecoverable errors
onProtocolMismatch(serverVersion: number, clientVersion: number) => voidCalled when the server protocol version does not match the client
maxReconnectAttemptsnumberMax WebSocket reconnection attempts (default: 10)
initialReconnectDelaynumberInitial delay in ms before first reconnect (default: 1000)
maxReconnectDelaynumberMaximum delay in ms between reconnects (default: 30000)
authTimeoutnumberTimeout in ms for auth handshake (default: 10000)

createValetProvider Config

createValetProvider is the standard way to set up Valet in a React app. It creates a configured ValetProvider component and typed hooks. Codegen produces this call for you in _generated/valet/react.ts.

_generated/valet/react.ts
import { createValetProvider } from 'valet-dev/react'
import { handlers } from './handlers'
import schema from './schema.json'

export const { ValetProvider, useQuery, useMutation } = createValetProvider({
    schema: schema,
    handlers: handlers,
    dbName: 'valet.db',
    locateWasm: (file) => `/${file}`,
})
OptionTypeDescription
schemaJsonSchema | SyncSchemaSchema definition from schema.json (codegen output) or defineSchema
handlersHandlerRegistryHandler registry from generated handlers.js for local execution
dbNamestringName of the local SQLite database (default: 'valet.db')
locateWasm(file: string) => stringFunction to resolve WASM file paths. Returns a URL path for the given filename. Default prepends / to the filename.

Generated ValetProvider Props

The ValetProvider component returned by createValetProvider accepts these props:

App.tsx
import { ValetProvider } from './_generated/valet/react'

function App() {
    return (
        <ValetProvider
            url={process.env.VALET_PROJECT_URL!}
            authToken={async () => getToken()}
            authRefreshBuffer={60000}
            onConnectionChange={(state) => console.log(state)}
            onAuthStateChange={(state, userId) => console.log(state, userId)}
            onError={(error) => console.error(error)}
            onProtocolMismatch={(server, client) =>
                console.warn(server, client)
            }
            loadingFallback={<LoadingScreen />}
            errorFallback={(error) => <ErrorScreen error={error} />}
        >
            <MyApp />
        </ValetProvider>
    )
}
PropTypeDescription
urlstringServer URL — accepts HTTP or WebSocket formats (required)
authTokenstring | () => Promise<string>Static token or async function that returns a token
authRefreshBuffernumberMilliseconds before token expiry to trigger refresh (default: 60000)
onConnectionChange(state: ConnectionState) => voidCalled when connection state changes
onAuthStateChange(state: AuthState, userId?: string, error?: AuthError) => voidCalled when auth state changes
onError(error: Error) => voidCalled on unrecoverable errors
onProtocolMismatch(serverVersion: number, clientVersion: number) => voidCalled on protocol version mismatch
loadingFallbackReactNodeContent to show while initializing (default: null)
errorFallbackReactNode | ((error: Error) => ReactNode)Content to show on initialization error (default: null)
childrenReactNodeChild components (required)

Metro Config (React Native)

For Expo and React Native projects, wrap your Metro config with withValet:

metro.config.js
const { getDefaultConfig } = require('expo/metro-config')
const { withValet } = require('valet-dev/metro')

module.exports = withValet(getDefaultConfig(__dirname))

withValet enables package exports resolution and adds .wasm to the asset extensions list. Both are required for the SQLite WASM module to load correctly on web builds.

Logger Configuration

Control logging behavior globally for all Valet SDK loggers.

app.ts
import { configureLogger, LogLevel } from 'valet-dev'

// Disable all logging in production
if (process.env.NODE_ENV === 'production') {
    configureLogger({ enabled: false })
}

// Only show warnings and errors
configureLogger({ level: LogLevel.WARN })

// Enable debug logging for development
configureLogger({ level: LogLevel.DEBUG })

// Check current configuration
const config = getLoggerConfig()
console.log(config) // { enabled: true, level: 0 }

// Reset to defaults
resetLoggerConfig()
FunctionDescription
configureLoggerSet global log level and enabled state for all loggers
getLoggerConfigGet current global configuration
resetLoggerConfigReset to defaults (enabled: true, level: INFO)
LogLevel.DEBUGLog level 0 — most verbose
LogLevel.INFOLog level 1 — default level
LogLevel.WARNLog level 2 — warnings only
LogLevel.ERRORLog level 3 — errors only

Note: Individual loggers can override global settings by passing explicit options to createLogger().

Credential Priority

When resolving credentials, the CLI checks sources in this order:

For valet deploy (schema and handler push):

  1. Environment variables
  2. .env.production
  3. .env

For valet codegen:

  1. Environment variables
  2. .env

On this page