Skip to content

Repository files navigation

nuxt-ui-mongocamp

npm versionnpm downloadsLicenseNuxtDocs

A Nuxt module that wraps @sfxcode/nuxt-mongocamp-server with ready-made UI components, composables, and a runtime plugin. Add the module to your Nuxt app and get MongoCamp authentication, user/role management, and collection access out of the box — built on Nuxt UI and FormKit.

Features

  • Auth middleware — global route guard that protects /secured/** (login required) and /admin/** (admin role required)
  • Ready-made components — login form, user/role management tables, collection browser with stats and paginated data table, server version badge
  • FormKit-powered forms — schema-driven forms via @sfxcode/nuxt-ui-formkit with nuxtUIInput, nuxtUISwitch, nuxtUIListbox, and nuxtUISelectMenu inputs
  • ComposablesuseMongocampAdmin, useMongocampCollection, useMongocampDocument, useMongocampSchema auto-imported into your app
  • Zero extra config — peer modules (@nuxt/ui, @formkit/nuxt, unocss-nuxt-ui) are declared as moduleDependencies and configured automatically

Module Dependencies

These modules are declared as moduleDependencies and are automatically set up — you do not need to add them manually to your nuxt.config.ts:

ModulePurpose
@nuxt/uiComponent library (UTable, UModal, UBadge, UPageCard, …)
unocss-nuxt-uiUnoCSS preset that matches Nuxt UI's design tokens
@formkit/nuxtFormKit core integration for Nuxt
@sfxcode/nuxt-ui-formkitNuxt UI input types for FormKit (nuxtUIInput, nuxtUISwitch, nuxtUIListbox, nuxtUISelectMenu)
@sfxcode/nuxt-mongocamp-serverMongoCamp REST API client, auth state, and useMongocampApi() / useMongocampAuth() composables

Quick Setup

npm install @sfxcode/nuxt-ui-mongocamp

Add the module to nuxt.config.ts:

exportdefaultdefineNuxtConfig({modules: ['@sfxcode/nuxt-ui-mongocamp'],mongocamp: {url: process.env.MONGOCAMP_URL,},})

The mongocamp key is forwarded to @sfxcode/nuxt-mongocamp-server. Set MONGOCAMP_URL (and optionally MONGOCAMP_ADMIN_USER / MONGOCAMP_ADMIN_PASSWORD) in your .env file.

Components

All components are auto-imported.

<MongocampLogin />

FormKit schema-driven login form. Persists the last user ID in a cookie (mongocamp_login) and redirects to /secured on success.

<template>
<MongocampLogin />
</template>

<MongocampUsers />

Full CRUD table for managing users — create, edit (roles via transfer listbox, password change), and delete, all via modal dialogs. Includes a server-side debounced search input and sortable column headers.

<template>
<MongocampUsers />
</template>

<MongocampRoles />

Full CRUD table for managing roles — create, edit (admin flag, collection grants), and delete. Includes a server-side debounced search input and sortable column headers.

<template>
<MongocampRoles />
</template>

<MongocampRoleGrants />

Per-role collection grant management — lists grants for a named role, with add/edit/delete. Filters the collection picker to exclude already-granted collections.

<template>
<MongocampRoleGrants role-name="myRole" />
</template>

<MongocampCollections />

Table of all collections with document count, storage size, and index count. Each row links to the collection info and data pages. Includes a client-side filter input and sortable column headers.

PropTypeDefaultDescription
infoPathstring/secured/admin/collectionsBase path for the info page link
dataPathstring/secured/admin/collectionsBase path for the data page link (<dataPath>/<name>/data)
<template>
<MongocampCollections />
</template>

<MongocampCollectionInfos />

Stat-card grid for a single collection — document count, data size, storage size, avg doc size, index count, total index size, and a per-index size table.

<template>
<MongocampCollectionInfos collection-name="myCollection" />
</template>

<MongocampCollectionData />

Schema-driven paginated data table for a collection.

  • Columns derived from the collection's JSON schema; falls back to first-row key derivation when no schema properties exist. Column order: _id first, metaData last, all others sorted A–Z.
  • Sorting — clickable column headers trigger server-side sort via the MongoCamp API (field / -field).
  • Filtering — debounced search input sends a Lucene query (col1: *term* OR col2: *term*) across all string-typed columns to the API; disabled until the schema is loaded.
  • Cell rendering:
    • date-time columns and MongoDB $date extended JSON → locale-formatted date string
    • MongoDB $oid → monospaced ID string
    • metaData objects (with created/updated fields) → structured created / updated / by rows
    • All other objects and arrays → icon button ({} / list); click opens a modal with pretty-printed JSON in a <pre> tag
  • Includes a reload button and paginated footer.
<template>
<MongocampCollectionData collection-name="myCollection" />
</template>

<MongocampVersion />

Displays the connected MongoCamp server name and version as a UBadge. Shows a neutral "unavailable" badge when the server cannot be reached.

<template>
<MongocampVersion />
</template>

Composables

All composables are auto-imported.

useMongocampAdmin()

Wraps the adminApi and collectionApi for user and role management.

const{
listUsers,// (filter?: string) => Promise<UserProfile[]>
addUser,// (userId, password, apiKey?, roles?) => Promise<UserProfile>
deleteUser,// (userId) => Promise<void>
updateUserRoles,// (userId, roles) => Promise<UserProfile>
updateUserPassword,// (userId, password) => Promise<void>
listRoles,// (filter?: string) => Promise<Role[]>
addRole,// (name, isAdmin?, collectionGrants?) => Promise<Role>
updateRole,// (roleName, isAdmin, collectionGrants?) => Promise<Role>
deleteRole,// (roleName) => Promise<void>
listCollections,// () => Promise<string[]>}=useMongocampAdmin()

useMongocampCollection()

Reactive state for paginated collection queries.

const{
filter,// Ref<string | undefined> — MongoDB filter expression
sort,// Ref<string[] | undefined> — sort fields
projection,// Ref<string[] | undefined> — field projection
pagination,// Ref<{ pageIndex: number, pageSize: number }>
total,// Ref<number> — total document count}=useMongocampCollection()

useMongocampDocument()

Helpers for document-level operations.

const{
ensureMetaData,// <T>(data: T) => T — stamps createdBy/updatedBy/timestamps from logged-in user
updateFromPartial,// <T>(obj: T, updates: Partial<T>) => T}=useMongocampDocument()

useMongocampSchema()

Converts a JsonSchemaDefinition to typed table column definitions. Used internally by MongocampCollectionData.

const{ schemaToColumnDefinition }=useMongocampSchema()// schemaToColumnDefinition(definition, fields) => ColumnDefinition[]// ColumnDefinition: { columnName, columnKey, columnType }// columnType: 'string' | 'number' | 'date-time'

Fields are sorted with _id first, metaData last, and all other fields alphabetically.

Route Protection

Route protection is opt-in and config-driven via useMongocampRoles(). Set useGlobalAuthMiddleware: true and list your protected route globs under nuxtUiMongocamp — nothing is protected by default. See Route Protection for the full behavior.

Path patternRequirement
Matches securedRoutePartsUser must be logged in
Matches managementRoutePartsUser must be a manager (managerRoles, or admin)
Matches adminRoutePartsUser must be an admin
/logoutCalls logout()

On any unmet requirement, the middleware redirects to notAllowedPath (default '/'); /logout redirects to the separate logoutRedirectPath instead (also default '/'). Both are always themselves allowed, so neither can ever cause a redirect loop.

Runtime Plugin

The plugin provides $mongocampVersion (a Ref to the server's version info) via useNuxtApp():

const{ $mongocampVersion }=useNuxtApp()// $mongocampVersion.value?.name// $mongocampVersion.value?.version

Configuration

The module's own config key is nuxtUiMongocamp — it configures the route middleware described above:

nuxtUiMongocamp: {useGlobalAuthMiddleware: true,// default: falsenotAllowedPath: '/login',// default: '/'logoutRedirectPath: '/',// default: '/'managerRoles: ['support'],// default: []securedRouteParts: ['/secured/**'],// default: []managementRouteParts: ['/secured/manage/**'],// default: []adminRouteParts: ['/secured/admin/**'],// default: []useServerProxy: false,// default: false — see Server Proxy Auth belowserverProxyPath: '/api/_mongocamp',// default shown}

See Configuration for details on each option, and Server Proxy Auth for the api-key-only, no-login mode useServerProxy enables.

The MongoCamp server is configured separately, under the mongocamp key (provided by @sfxcode/nuxt-mongocamp-server):

mongocamp: {url: 'https://your-mongocamp-server',apiKey: process.env.MONGOCAMP_API_KEY,// optional, server-side only — required for server proxy auth modepaginationSize: 500,// default: 500refreshToken: true,// default: truetokenRefreshInterval: 5000,// ms, default: 5000}

Contribution

# Install dependencies
pnpm install
# Build stubs + prepare the playground (run once after clone)
pnpm run dev:prepare
# Start playground dev server
pnpm run dev
# Lint
pnpm run lint
# Run tests (Vitest + @nuxt/test-utils e2e)
pnpm run test
pnpm run test:watch
# Type-check
pnpm run test:types
# Build for publishing
pnpm run prepack

The playground reads playground/.env for MONGOCAMP_URL, MONGOCAMP_ADMIN_USER, and MONGOCAMP_ADMIN_PASSWORD. Optional vars demo server proxy auth mode: MONGOCAMP_API_KEY, MONGOCAMP_USE_SERVER_PROXY=true, and MONGOCAMP_PROXY_SHARED_SECRET (activates the example guard hook in playground/server/plugins/mongocamp-proxy-guard.ts).

Documentation

Full documentation (guides, components, composables) lives in docs/ and is built with VitePress:

# Start the docs dev server
pnpm run docs:dev
# Build the static site
pnpm run docs:build
# Preview the built site
pnpm run docs:preview

License

MIT

About

A Nuxt module that wraps mongocamp-server with ready-made UI components, composables, and a runtime plugin

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages