Server-side compatible versions of GraphQL and REST APIs for use in SSR environments like Next.js, providing the same functionality optimized for Node.js server contexts.
GraphQL client generation specifically designed for server-side rendering environments.
/**
* Generate GraphQL client for server-side usage
* @returns Server-compatible GraphQL client
*/
function generateClient(): ServerGraphQLClient;
/**
* Generate client with specific Amplify instance for advanced server usage
* @param amplifyInstance - Custom Amplify configuration instance
* @returns Server GraphQL client with custom configuration
*/
function generateClientWithAmplifyInstance(
amplifyInstance: AmplifyInstance
): ServerGraphQLClient;
interface ServerGraphQLClient {
/**
* Execute GraphQL operations on the server
*/
graphql<T>(
options: GraphQLOptionsV6<T>,
additionalHeaders?: CustomHeaders
): Promise<GraphQLResult<T>>;
/**
* Cancel server-side GraphQL operations
*/
cancel(promise: Promise<any>, message?: string): boolean;
/**
* Check if error is from cancellation
*/
isCancelError(error: any): boolean;
}Usage Examples:
// Next.js API route example
import { generateClient } from "@aws-amplify/api/server";
import { NextRequest } from "next/server";
export async function GET(request: NextRequest) {
const client = generateClient();
const { data, errors } = await client.graphql({
query: `
query ListTodos {
listTodos {
items {
id
content
completed
}
}
}
`
});
if (errors) {
return Response.json({ errors }, { status: 400 });
}
return Response.json({ data });
}
// With custom Amplify instance
import { Amplify } from "@aws-amplify/core";
import { generateClientWithAmplifyInstance } from "@aws-amplify/api/internals";
const amplify = Amplify.configure({
API: {
GraphQL: {
endpoint: process.env.GRAPHQL_ENDPOINT,
region: process.env.AWS_REGION,
defaultAuthMode: "iam"
}
}
});
const client = generateClientWithAmplifyInstance(amplify);Specialized client types for server-side rendering with different authentication strategies.
/**
* SSR client that uses cookies for authentication
*/
type V6ClientSSRCookies<T, Options = DefaultCommonClientOptions> = {
graphql: ServerGraphQLMethod<Options>;
cancel(promise: Promise<any>, message?: string): boolean;
isCancelError(error: any): boolean;
models: T extends Record<any, any> ? ModelOperations<T> : never;
};
/**
* SSR client that uses request context for authentication
*/
type V6ClientSSRRequest<T, Options = DefaultCommonClientOptions> = {
graphql: ServerGraphQLMethod<Options>;
cancel(promise: Promise<any>, message?: string): boolean;
isCancelError(error: any): boolean;
models: T extends Record<any, any> ? ModelOperations<T> : never;
};Complete set of HTTP methods optimized for server-side environments.
/**
* Server-side HTTP GET request
* @param contextSpec - Amplify server context specification
* @param input - Request configuration including API name and path
* @returns GetOperation promise that resolves to response
*/
function get(contextSpec: AmplifyServer.ContextSpec, input: GetInput): GetOperation;
/**
* Server-side HTTP POST request
* @param contextSpec - Amplify server context specification
* @param input - Request configuration including API name, path, and body
* @returns PostOperation promise that resolves to response
*/
function post(contextSpec: AmplifyServer.ContextSpec, input: PostInput): PostOperation;
/**
* Server-side HTTP PUT request
* @param contextSpec - Amplify server context specification
* @param input - Request configuration including API name, path, and body
* @returns PutOperation promise that resolves to response
*/
function put(contextSpec: AmplifyServer.ContextSpec, input: PutInput): PutOperation;
/**
* Server-side HTTP DELETE request
* @param contextSpec - Amplify server context specification
* @param input - Request configuration including API name and path
* @returns DeleteOperation promise that resolves to response
*/
function del(contextSpec: AmplifyServer.ContextSpec, input: DeleteInput): DeleteOperation;
/**
* Server-side HTTP PATCH request
* @param contextSpec - Amplify server context specification
* @param input - Request configuration including API name, path, and body
* @returns PatchOperation promise that resolves to response
*/
function patch(contextSpec: AmplifyServer.ContextSpec, input: PatchInput): PatchOperation;
/**
* Server-side HTTP HEAD request
* @param contextSpec - Amplify server context specification
* @param input - Request configuration including API name and path
* @returns HeadOperation promise that resolves to response with headers only
*/
function head(contextSpec: AmplifyServer.ContextSpec, input: HeadInput): HeadOperation;
/**
* Check if error is from request cancellation
*/
function isCancelError(error: unknown): boolean;Usage Examples:
// Next.js server action example
import { post } from "@aws-amplify/api/server";
import { createServerRunner } from "@aws-amplify/adapter-nextjs";
const { runWithAmplifyServerContext } = createServerRunner({
config: amplifyServerConfig
});
export async function createUser(formData: FormData) {
"use server";
const userData = {
name: formData.get("name"),
email: formData.get("email")
};
return await runWithAmplifyServerContext({
nextServerContext: { cookies },
operation: (contextSpec) => {
try {
const response = await post(contextSpec, {
apiName: "userApi",
path: "/users",
options: {
body: userData,
headers: {
"Content-Type": "application/json"
}
}
});
return { success: true, data: response.body };
} catch (error) {
return { success: false, error: error.message };
}
}
});
}The AmplifyServer.ContextSpec type required for all server-side operations.
/**
* Server context specification for Amplify operations
*/
namespace AmplifyServer {
interface ContextSpec {
token: {
value: ContextToken;
};
}
interface ContextToken {
libraryOptions: LibraryOptions;
userAgentSuffix?: string;
}
}Configuration options specific to server-side usage.
interface ServerApiConfig {
/**
* Server-side authentication configuration
*/
auth?: {
/**
* AWS credentials for server-side requests
*/
credentials?: AWSCredentials;
/**
* IAM role for server-side authentication
*/
region?: string;
/**
* Custom authentication headers
*/
customHeaders?: Record<string, string>;
};
/**
* Request timeout for server operations
*/
timeout?: number;
/**
* Custom user agent for server requests
*/
userAgent?: string;
/**
* Server-side retry configuration
*/
retryConfig?: ServerRetryConfig;
}
interface ServerRetryConfig {
maxRetries?: number;
baseDelay?: number;
maxDelay?: number;
jitter?: boolean;
}
interface AWSCredentials {
accessKeyId: string;
secretAccessKey: string;
sessionToken?: string;
}Integration with server frameworks and request contexts.
/**
* Server context for passing request information
*/
interface ServerContext {
/**
* HTTP request object
*/
request?: {
headers: Record<string, string>;
url: string;
method: string;
};
/**
* User authentication context
*/
user?: {
id: string;
email?: string;
groups?: string[];
};
/**
* Request tracing information
*/
tracing?: {
traceId: string;
spanId: string;
};
}
/**
* Context-aware server operations
*/
interface ContextualServerAPI {
/**
* Execute operation with server context
*/
withContext<T>(
context: ServerContext,
operation: () => Promise<T>
): Promise<T>;
/**
* Get current server context
*/
getContext(): ServerContext | null;
}Usage Examples:
// Express.js middleware example
import { generateClient } from "@aws-amplify/api/server";
app.use(async (req, res, next) => {
const client = generateClient();
// Add client to request context
req.amplifyClient = client;
// Execute with server context
const result = await client.withContext({
request: {
headers: req.headers,
url: req.url,
method: req.method
},
user: req.user
}, async () => {
// Operations here have access to server context
return client.graphql({
query: "query GetUserData { getCurrentUser { id name } }"
});
});
next();
});Error handling patterns specific to server environments.
/**
* Server-specific error types
*/
interface ServerApiError extends Error {
/**
* HTTP status code for the error
*/
statusCode?: number;
/**
* Error code for categorization
*/
code?: string;
/**
* Request ID for tracking
*/
requestId?: string;
/**
* Whether error should be retried
*/
retryable?: boolean;
/**
* Additional error context
*/
context?: Record<string, any>;
}
/**
* Server authentication errors
*/
interface ServerAuthError extends ServerApiError {
/**
* Authentication failure reason
*/
authFailure: "credentials" | "permissions" | "expired" | "invalid";
/**
* Required permissions for the operation
*/
requiredPermissions?: string[];
}Utilities for detecting and adapting to server environments.
/**
* Server environment detection utilities
*/
interface ServerEnvironment {
/**
* Check if running in server environment
*/
isServer(): boolean;
/**
* Check if running in specific frameworks
*/
isNextJS(): boolean;
isExpress(): boolean;
isLambda(): boolean;
/**
* Get current runtime information
*/
getRuntime(): {
platform: string;
version: string;
framework?: string;
};
}