@egdesk/next-api-plugin
v1.5.64
Published
Next.js plugin for EGDesk database proxy integration
Maintainers
Readme
@egdesk/next-api-plugin
Next.js plugin for EGDesk database proxy integration. Provides middleware-based CORS-free database access for Next.js applications.
Features
- 🔒 CORS-free database access via Next.js middleware (or
proxy.tson Next.js 16+) - 🌐 Works in both local and tunneled environments
- 📝 Type-safe table definitions and helper functions (user data, FinanceHub, internal knowledge / business identity / company research, browser recording replay + live browse)
- 🚀 Auto-discovery of database tables
- 🔧 Zero configuration after setup
Installation
npm install @egdesk/next-api-plugin
# or
yarn add @egdesk/next-api-plugin
# or
pnpm add @egdesk/next-api-pluginQuick Start
- Run the setup command in your Next.js project:
npx egdesk-next-setupThis will generate:
middleware.tsorproxy.ts- Database proxy (includes visitor auth/google)egdesk.config.ts- Type-safe table definitionsegdesk-helpers.ts- Helper functions for database accessegdesk-visitor-google.ts- Visitor Google login helper (generated — do not edit)egdesk.visitor-auth.ts- Site-owned login defaults (created once, never overwritten)app/auth/callback/page.tsx- Exchanges EGDesk’s one-time login code (generated — do not edit).env.local- Environment variables (NEXT_PUBLIC_EGDESK_*only — no Supabase keys)
Add {EGDesk public URL}/visitor-auth/callback to the EGDesk Supabase Auth redirect allowlist (once per EGDesk/tunnel origin, not each published site).
Add
.env.localto your.gitignore(if not already there)Restart your Next.js dev server
Use the helpers in your components:
import { queryTable } from './egdesk-helpers';
import { TABLES } from './egdesk.config';
export default async function MyPage() {
const data = await queryTable(TABLES.table1.name, { limit: 10 });
return (
<div>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}Configuration
Environment Variables
The plugin uses Next.js environment variables:
NEXT_PUBLIC_EGDESK_API_URL=http://localhost:8080
NEXT_PUBLIC_EGDESK_API_KEY=your-api-key-herePublished sites do not receive SUPABASE_URL or the anon key. Visitor Google sign-in is brokered by EGDesk: the site redirects through {EGDESK_API}/visitor-auth, EGDesk creates an Auth user, and the site stores an opaque session id bound to this site's origin. Another published site on the same EGDesk cannot reuse that session.
Add the EGDesk callback (not each site origin) to Supabase → Authentication → URL Configuration → Redirect URLs:
- Local:
http://localhost:54321/auth/callback - Tunnel:
https://tunneling-service.onrender.com/t/{tunnelId}/visitor-auth/callbackorhttps://tunneling-service.onrender.com/**
Do not add ?vid= — extra query params make Supabase fall back to the Site URL (egdesk.cloud).
Owner MCP (startDriveAuthLogin) is a separate credential on the EGDesk machine. Visitor login does not overwrite it.
Visitor login: generated vs site-owned
| File | Owner | Overwritten on codegen? |
|------|--------|-------------------------|
| egdesk-visitor-google.ts | EGDesk plugin | Yes |
| app/auth/callback/page.tsx | EGDesk plugin | Yes |
| egdesk.visitor-auth.ts | The site | No |
| app/login/page.tsx (or any custom UI) | The site | Never generated |
Do not copy helper constants into src/ to survive regeneration. Import presets and pass them:
import {
startVisitorGoogleLogin,
VISITOR_BASIC_SCOPES,
VISITOR_WORKSPACE_SCOPES,
} from './egdesk-visitor-google';
// Sign-in only (smaller Google consent)
await startVisitorGoogleLogin({ next: '/dashboard', scopes: VISITOR_BASIC_SCOPES });
// Drive / Sheets / Docs / Slides
await startVisitorGoogleLogin({ next: '/drive', scopes: VISITOR_WORKSPACE_SCOPES });Project default (never overwritten):
// egdesk.visitor-auth.ts
export const VISITOR_AUTH = {
scopes: 'basic' as 'basic' | 'workspace',
};NEXT_PUBLIC_EGDESK_VISITOR_SCOPES=basic|workspace overrides that file. You can also pass any Google scopes to startVisitorGoogleLogin({ scopes }). Identity scopes are always included. Older helpers that send no scopes still get workspace (previous default).
To use those visitor credentials on Workspace MCP (Sheets / Drive / Docs / Slides / Gmail / Apps Script), pass { asVisitor: true } to the helper. Owner credentials stay the default.
import { callSheetsTool, getSheetRange } from './egdesk-helpers';
// Owner EGDesk credentials (default)
await getSheetRange(spreadsheetId, 'Sheet1!A1:B2');
// Website visitor from startVisitorGoogleLogin() (browser)
await callSheetsTool('sheets_get_range', { spreadsheetId, range: 'Sheet1!A1:B2' }, { asVisitor: true });
// Server / terminal: session + the origin the visitor logged in from
await callSheetsTool(
'sheets_get_range',
{ spreadsheetId, range: 'Sheet1!A1:B2' },
{
asVisitor: true,
visitorSessionId,
visitorOrigin: 'http://localhost:4003',
},
);On the server, window is missing so EGDesk cannot infer the site. Pass visitorOrigin or set NEXT_PUBLIC_EGDESK_VISITOR_ORIGIN (falls back to NEXT_PUBLIC_SITE_URL). It must match the origin used at login. The API key authenticates this EGDesk instance; it does not replace origin.
Watch / sync / drive_auth_login stay owner-only even with asVisitor.
Custom Setup
You can programmatically run the setup:
import { setupNextApiPlugin } from '@egdesk/next-api-plugin';
await setupNextApiPlugin('/path/to/project', {
egdeskUrl: 'http://localhost:8080',
apiKey: 'optional-api-key'
});How It Works
The plugin generates middleware.ts or proxy.ts that intercepts special paths and forwards them to your EGDesk HTTP MCP server so the browser never talks to another origin directly.
Proxied paths (examples):
| Path | Forwards to |
|------|-------------|
| __user_data_proxy | POST /user-data/tools/call |
| __browser_recording_proxy | POST /browser-recording/tools/call |
Browser recording file upload: listBrowserRecordingSites → openBrowserRecordingAccount (navigate-only sites use accountKey: "__unknown_account__") → inspectBrowserRecordingPage → uploadBrowserRecordingFile(sessionId, absPath, elementIndex?). Prefer the hidden [file input] index. filePath must exist on the EGDesk machine. Persist with saveBrowserRecordingSession. Replay override: fileUploadsByIndex.
| __internal_knowledge_proxy | POST /internal-knowledge/tools/call (knowledge docs, business identity snapshots, company research) |
User-data request flow:
- Your code calls
queryTable()or another helper - Helper fetches
__user_data_proxy - Middleware/proxy forwards to
http://<EGDESK>/user-data/tools/call - Parsed JSON is returned to your component
API Reference
Helper Functions
// Query table data
queryTable(tableName: string, options?: {
filters?: Record<string, string>;
limit?: number;
offset?: number;
orderBy?: string;
orderDirection?: 'ASC' | 'DESC';
})
// Search table
searchTable(tableName: string, searchQuery: string, limit?: number)
// Aggregate data
aggregateTable(tableName: string, column: string, aggregateFunction: 'SUM' | 'AVG' | 'MIN' | 'MAX' | 'COUNT', options?: {
filters?: Record<string, string>;
groupBy?: string;
})
// Execute raw SQL
executeSQL(query: string)
// List all tables
listTables()
// Get table schema
getTableSchema(tableName: string)
// Internal Knowledge / Business Identity / Company Research (MCP)
callInternalKnowledgeTool(toolName: string, args?: Record<string, any>)
listKnowledgeDocuments(snapshotId: string, category?: 'hierarchy' | 'process' | 'policy' | 'note')
getKnowledgeDocument(documentId: string)
searchKnowledgeContent(snapshotId: string, searchText: string, category?: ...)
getKnowledgeByCategory(snapshotId: string, category: ...)
listBusinessIdentitySnapshots(brandKey?: string)
getBusinessIdentitySnapshot(snapshotId: string)
getBusinessIdentityCompanyInfo(snapshotId: string)
getBusinessIdentityServicesProducts(snapshotId: string)
listCompanyResearch(status?: 'completed' | 'failed' | 'in_progress')
getCompanyResearchById(researchId: string)
getCompanyResearchByDomain(domain: string)
searchCompanyResearch(searchText: string)
// Owner Drive MCP (THIS EGDesk instance)
startDriveAuthLogin()
getDriveAuthStatus()
// Visitor Google — import from egdesk-visitor-google.ts, not egdesk-helpers.ts
startVisitorGoogleLogin({ scopes: VISITOR_BASIC_SCOPES })
startVisitorGoogleLogin({ scopes: VISITOR_WORKSPACE_SCOPES })
getVisitorGoogleStatus()
listVisitorDriveFiles()
getVisitorSheetRange(spreadsheetId, range)Visitor Google vs owner MCP
| Who | Helper | Identity |
|-----|--------|----------|
| EGDesk owner | startDriveAuthLogin() / callSheetsTool() (default) | Owner token for this machine’s MCP (Drive watch, sync) |
| Website visitor | startVisitorGoogleLogin() then callSheetsTool(..., { asVisitor: true }) | Opaque visitor session (brokered by EGDesk; bound to this site origin) |
Visitors are EGDesk Auth users. They are not the MCP owner unless you opt in with asVisitor. The published site never holds Supabase credentials or Google tokens.
Configuration Types
interface TableDefinition {
name: string;
displayName: string;
description?: string;
rowCount: number;
columnCount: number;
columns: string[];
}
const TABLES = {
table1: TableDefinition,
table2: TableDefinition,
// ...
}
const TABLE_NAMES = {
table1: 'actual_table_name',
table2: 'another_table_name',
// ...
}Troubleshooting
Middleware not working
Make sure:
middleware.tsis in your project root (not insrc/orapp/)- Your Next.js version is 13.0.0 or higher
- You've restarted your dev server after setup
CORS errors
If you're still seeing CORS errors:
- Check that middleware.ts was generated correctly
- Verify environment variables are set in
.env.local - Make sure you're using the relative URL
__user_data_proxy(no leading slash)
Table discovery fails
Ensure:
- EGDesk MCP server is running on
localhost:8080 - You have tables imported in EGDesk
- API key is correct (if required)
License
MIT
