DEV Community

Cover image for Master Clean Code in AWS SAM: Using Shared Folders
Márcio Coelho
Márcio Coelho

Posted on

Master Clean Code in AWS SAM: Using Shared Folders

As projects grow, maintaining a clean structure is essential. In this post, we will:

✅ Create a centralized shared folder
✅ Configure esbuild to support module aliases for cleaner imports
✅ Using TypeScript for development


🗂️ Step 1: Create a shared Folder

Let’s create a folder for all shared utilities and modules.

aws-sam-node-lambda/
├── shared/
│   ├── utils.ts
│   ├── constants.ts
├── functions/
|   ├── function1/
│   |   ├── index.ts
├── tsconfig.json
└── template.yaml
Enter fullscreen mode Exit fullscreen mode

shared/utils.ts

export const greet = (name: string) => `Hello, ${name}!`;
Enter fullscreen mode Exit fullscreen mode

📝 Step 2: Lambda Code to Use Shared Module

In your Lambda handler:

import { greet } from '@shared/utils';

export const handler = async () => {
    const message = greet('AWS Lambda');
    return {
        statusCode: 200,
        body: JSON.stringify({ message })
    };
};
Enter fullscreen mode Exit fullscreen mode

⚙️ Step 3: Configure TypeScript Path Aliases

Edit your tsconfig.json to define path aliases:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@shared/*": ["shared/*"]
    },
    "module": "ESNext",
    "target": "ES2020",
    "moduleResolution": "Node",
    "outDir": "dist",
    "esModuleInterop": true
  }
}
Enter fullscreen mode Exit fullscreen mode

⚡ Step 4: Configure esbuild

In your template.yaml, configure esbuild under Metadata -> BuildMethod: esbuild:

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs22.x
      Architectures:
        - arm64
    Metadata:
      BuildMethod: esbuild
      BuildProperties:
        Minify: true
        Target: "es2020"
        Sourcemap: true
        EntryPoints:
          - functions/function1/handler.ts
        External:
          - "@aws-sdk/*"
Enter fullscreen mode Exit fullscreen mode

🧠 Conclusion

By organizing your code with a shared folder and aliases, you can improve maintainability and scalability for your AWS Lambda projects. Coupled with esbuild and TypeScript, this setup is modern, fast, and production-ready.

Top comments (0)