npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@dyanet/nextjs-config-aws

v1.1.1

Published

Next.js adapter for AWS configuration management with support for server components, runtime environment variables, and AWS services integration

Readme

@dyanet/nextjs-config-aws

npm version CI codecov License: MIT

Next.js adapter for AWS configuration management. A thin wrapper around @dyanet/config-aws that provides server-side configuration loading, runtime environment variables, and automatic environment detection.

Features

  • Simplified API - Just getConfig(), PublicEnvScript, and env() - no loader complexity
  • Automatic Environment Detection - Configures itself based on NODE_ENV
  • Runtime Environment Variables - Deploy the same build to different environments
  • Caching - Avoid repeated AWS API calls during request handling
  • Type Safety - Full TypeScript support with Zod schema validation
  • AWS Services - Load configuration from Secrets Manager and SSM Parameter Store

Installation

npm install @dyanet/nextjs-config-aws

Peer Dependencies

npm install next react

For AWS services, install the SDK clients you need:

# For Secrets Manager
npm install @aws-sdk/client-secrets-manager

# For SSM Parameter Store
npm install @aws-sdk/client-ssm

# For schema validation
npm install zod

Quick Start

Server-Side Configuration

// app/page.tsx (Server Component)
import { getConfig } from '@dyanet/nextjs-config-aws';
import { z } from 'zod';

const schema = z.object({
  DATABASE_URL: z.string(),
  API_KEY: z.string(),
});

export default async function Page() {
  // Minimal usage - auto-detects environment
  const config = await getConfig({ schema });

  return <div>Connected to: {config.DATABASE_URL}</div>;
}

With AWS Secrets Manager

// app/page.tsx
import { getConfig } from '@dyanet/nextjs-config-aws';
import { z } from 'zod';

const schema = z.object({
  DATABASE_URL: z.string(),
  API_KEY: z.string(),
});

export default async function Page() {
  const config = await getConfig({
    schema,
    aws: { 
      secretName: '/my-app/config',
      region: 'us-east-1'  // Optional, defaults to AWS_REGION env var
    },
  });

  return <div>Connected to: {config.DATABASE_URL}</div>;
}

Runtime Environment Variables

// app/layout.tsx
import { PublicEnvScript } from '@dyanet/nextjs-config-aws';

export default function RootLayout({ children }) {
  return (
    <html>
      <head>
        <PublicEnvScript
          publicVars={['API_URL', 'APP_NAME', 'FEATURE_FLAGS']}
        />
      </head>
      <body>{children}</body>
    </html>
  );
}
// app/components/client-component.tsx
'use client';

import { env } from '@dyanet/nextjs-config-aws';

export function ClientComponent() {
  const apiUrl = env('API_URL');
  const appName = env('APP_NAME', 'My App');

  return <div>API: {apiUrl}, App: {appName}</div>;
}

Environment Detection

The library automatically configures itself based on NODE_ENV:

| Environment | Env Vars | .env Files | AWS Sources | |-------------|----------|------------|-------------| | development | ✓ | .env.local, .env | Only if forceAwsInDev: true | | production | ✓ | .env | ✓ (if configured) | | test | ✓ | ✗ | ✗ |

Override Environment Detection

const config = await getConfig({
  schema,
  environment: 'production',  // Force production behavior
});

Force AWS in Development

const config = await getConfig({
  schema,
  aws: { secretName: '/my-app/config' },
  forceAwsInDev: true,  // Load from AWS even in development
});

API Reference

getConfig()

Load configuration in Server Components, API routes, or server actions.

import { getConfig } from '@dyanet/nextjs-config-aws';

Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | schema | ZodType<T> | undefined | Zod schema for validation | | aws.secretName | string | undefined | AWS Secrets Manager secret name | | aws.ssmPrefix | string | undefined | AWS SSM Parameter Store path prefix | | aws.region | string | AWS_REGION | AWS region for all service calls | | environment | 'development' \| 'production' \| 'test' | auto-detect | Override environment detection | | forceAwsInDev | boolean | false | Load from AWS in development mode | | cache | boolean | true | Enable caching | | cacheTTL | number | 60000 | Cache TTL in milliseconds |

Examples

// Minimal - just schema
const config = await getConfig({ schema });

// With AWS Secrets Manager
const config = await getConfig({
  schema,
  aws: { secretName: '/my-app/secrets' }
});

// With SSM Parameter Store
const config = await getConfig({
  schema,
  aws: { ssmPrefix: '/my-app/config' }
});

// Both AWS sources
const config = await getConfig({
  schema,
  aws: { 
    secretName: '/my-app/secrets',
    ssmPrefix: '/my-app/config',
    region: 'us-west-2'
  }
});

// Disable caching
const config = await getConfig({
  schema,
  cache: false
});

PublicEnvScript

Server component that injects environment variables into the client.

import { PublicEnvScript } from '@dyanet/nextjs-config-aws';

Props

| Prop | Type | Default | Description | |------|------|---------|-------------| | publicVars | string[] | undefined | Explicit list of variables to expose | | publicPrefix | string | undefined | Prefix to filter variables | | variableName | string | '__ENV' | Global variable name on window | | nonce | string | undefined | CSP nonce for script tag |

Security Note: Only expose variables that are safe for public access. Never expose secrets, API keys, or sensitive data.

// Explicit allowlist
<PublicEnvScript publicVars={['API_URL', 'APP_NAME']} />

// Prefix filtering
<PublicEnvScript publicPrefix="PUBLIC_" />

// With CSP nonce
<PublicEnvScript publicVars={['API_URL']} nonce={cspNonce} />

env()

Access runtime environment variables on the client.

'use client';

import { env } from '@dyanet/nextjs-config-aws';
// Get a variable (returns undefined if not found)
const apiUrl = env('API_URL');

// Get with default value
const appName = env('APP_NAME', 'My App');

Error Handling

import { ConfigurationError, ValidationError } from '@dyanet/nextjs-config-aws';

try {
  const config = await getConfig({ schema });
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Validation failed:', error.message);
    // error.message includes the invalid/missing key names
  }
}

App Router Examples

Server Component

// app/dashboard/page.tsx
import { getConfig } from '@dyanet/nextjs-config-aws';
import { z } from 'zod';

const schema = z.object({
  DATABASE_URL: z.string(),
  FEATURE_FLAGS: z.string().transform(s => JSON.parse(s)),
});

export default async function DashboardPage() {
  const config = await getConfig({
    schema,
    aws: { ssmPrefix: '/app/config' },
  });

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Features: {JSON.stringify(config.FEATURE_FLAGS)}</p>
    </div>
  );
}

API Route

// app/api/config/route.ts
import { NextResponse } from 'next/server';
import { getConfig } from '@dyanet/nextjs-config-aws';
import { z } from 'zod';

const schema = z.object({
  API_VERSION: z.string(),
  MAX_REQUESTS: z.coerce.number(),
});

export async function GET() {
  const config = await getConfig({ schema });

  return NextResponse.json({
    version: config.API_VERSION,
    maxRequests: config.MAX_REQUESTS,
  });
}

Server Action

// app/actions.ts
'use server';

import { getConfig } from '@dyanet/nextjs-config-aws';
import { z } from 'zod';

const schema = z.object({
  API_KEY: z.string(),
});

export async function fetchData() {
  const config = await getConfig({
    schema,
    aws: { secretName: '/app/secrets' },
  });

  const response = await fetch('https://api.example.com/data', {
    headers: { 'Authorization': `Bearer ${config.API_KEY}` },
  });

  return response.json();
}

Pages Router Examples

getServerSideProps

// pages/dashboard.tsx
import { getConfig } from '@dyanet/nextjs-config-aws';
import { z } from 'zod';
import type { GetServerSideProps } from 'next';

const schema = z.object({
  API_URL: z.string(),
});

export const getServerSideProps: GetServerSideProps = async () => {
  const config = await getConfig({ schema });

  return {
    props: {
      apiUrl: config.API_URL,
    },
  };
};

export default function Dashboard({ apiUrl }: { apiUrl: string }) {
  return <div>API URL: {apiUrl}</div>;
}

API Route (Pages Router)

// pages/api/config.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { getConfig } from '@dyanet/nextjs-config-aws';
import { z } from 'zod';

const schema = z.object({
  APP_VERSION: z.string(),
});

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const config = await getConfig({ schema });

  res.json({ version: config.APP_VERSION });
}

Advanced Usage

For advanced use cases such as custom loaders, direct AWS SDK integration, or fine-grained control over configuration loading, import from @dyanet/config-aws directly:

import {
  ConfigManager,
  EnvironmentLoader,
  EnvFileLoader,
  SecretsManagerLoader,
  SSMParameterStoreLoader,
  S3Loader,
} from '@dyanet/config-aws';

const manager = new ConfigManager({
  loaders: [
    new EnvironmentLoader({ prefix: 'APP_' }),
    new EnvFileLoader({ paths: ['.env.local', '.env'] }),
    new SecretsManagerLoader({ secretName: '/my-app/config' }),
  ],
  schema: mySchema,
  precedence: 'aws-first',
});

await manager.load();
const config = manager.getAll();

Related Packages

License

MIT