@lattice.black/plugin-nextjs
Version:
Lattice service discovery plugin for Next.js applications
211 lines (155 loc) • 5.27 kB
Markdown
Lattice plugin for Next.js applications. Automatically discovers API routes and dependencies, then submits to the Lattice collector for visualization.
**⚠️ Server-Only Package**: This plugin uses Node.js file system APIs and can only run on the server. It should be used in:
- `instrumentation.ts` (recommended)
- Server Components
- API Routes
- Server Actions
```bash
yarn add @lattice.black/plugin-nextjs
npm install @lattice.black/plugin-nextjs
```
**IMPORTANT**: You must add this package to `serverComponentsExternalPackages` to prevent webpack bundling errors:
```javascript
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
instrumentationHook: true,
},
serverComponentsExternalPackages: ['@lattice.black/plugin-nextjs'],
}
export default nextConfig;
```
> Without `serverComponentsExternalPackages`, Next.js will try to bundle this server-only package for the browser, causing "Module not found" errors for Node.js APIs.
Create `src/instrumentation.ts` in your Next.js project:
```typescript
import { LatticeNextPlugin } from '@lattice.black/plugin-nextjs';
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
console.log('🔍 Initializing Lattice plugin for Next.js...');
const lattice = new LatticeNextPlugin({
serviceName: 'my-nextjs-app',
environment: 'development',
apiEndpoint: 'http://localhost:3000/api/v1',
enabled: true,
autoSubmit: true,
onAnalyzed: (metadata) => {
console.log('📊 Service metadata analyzed:', {
service: metadata.service.name,
routes: metadata.routes?.length,
dependencies: metadata.dependencies?.length,
});
},
onSubmitted: (response) => {
console.log('✅ Metadata submitted to Lattice:', response.serviceId);
},
onError: (error) => {
console.error('❌ Lattice error:', error.message);
},
});
try {
await lattice.analyze();
} catch (error) {
console.error('Failed to analyze service:', error);
}
}
}
```
Create a file in your Next.js project (e.g., `lib/lattice.ts`):
```typescript
import { LatticeNextPlugin } from '@lattice.black/plugin-nextjs';
const lattice = new LatticePlugin({
serviceName: 'my-nextjs-app',
apiKey: process.env.LATTICE_API_KEY,
});
export async function registerLattice() {
await lattice.analyze();
return lattice;
}
```
Then in your root layout or startup file:
```typescript
import { registerLattice } from '@/lib/lattice';
// In server component or API route
registerLattice().catch(console.error);
```
Add to `pages/_app.tsx`:
```typescript
import { LatticePlugin } from '@lattice/plugin-nextjs';
import { useEffect } from 'react';
function MyApp({ Component, pageProps }) {
useEffect(() => {
if (typeof window === 'undefined') {
const lattice = new LatticePlugin();
lattice.analyze().catch(console.error);
}
}, []);
return <Component {...pageProps} />;
}
```
```typescript
const lattice = new LatticePlugin({
// Service identity
serviceName: 'my-nextjs-app', // Auto-detected if not provided
environment: 'production', // Defaults to NODE_ENV
// API connection
apiEndpoint: 'https://lattice-production.up.railway.app/api/v1',
apiKey: process.env.LATTICE_API_KEY,
// Behavior
enabled: true, // Enable/disable plugin
autoSubmit: true, // Auto-submit on analyze
submitInterval: 300000, // Re-submit every 5 minutes
// Discovery options
discoverRoutes: true,
discoverDependencies: true,
// Next.js specific
appDir: 'app', // App Router directory
pagesDir: 'pages', // Pages Router directory
// Callbacks
onAnalyzed: (metadata) => {
console.log(`Discovered ${metadata.routes.length} routes`);
},
onSubmitted: (response) => {
console.log(`Submitted: ${response.serviceId}`);
},
onError: (error) => {
console.error('Lattice error:', error);
},
});
```
```bash
LATTICE_SERVICE_NAME=my-nextjs-app
LATTICE_API_ENDPOINT=https://lattice-production.up.railway.app/api/v1
LATTICE_API_KEY=your-api-key
LATTICE_ENABLED=true
```
Analyze Next.js app and discover API routes and dependencies.
Submit metadata to Lattice collector API.
Get currently analyzed metadata.
Start auto-submit interval.
Stop auto-submit interval.
The plugin automatically discovers:
- **App Router**: `app/api/**/*.ts` route handlers
- **Pages Router**: `pages/api/**/*.ts` API routes
- Dynamic routes: `[param]`, `[...slug]`
- Route groups: `(group)`
- Catch-all routes
MIT