dherault / dherault/serverless-offline

esbuild define constants not respected when using `serverless offline start`

Open
#1,856 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
5.3k
Forks
811
Avg merge
2d 4h
Merged PRs (30d)
3

Description

## Bug Report

**Current Behavior**

When using serverless-offline with serverless framework v4 and esbuild to define constants using the define option in serverless.yml, the constants are not correctly replaced when running the command `serverless offline start`, which results in a ReferenceError at runtime due to the undefined constant. However, the constants are properly replaced when using `serverless offline`.

**Sample Code**

- file: serverless.yml

```yaml
service: my-api
frameworkVersion: '4'

provider:
name: aws
runtime: nodejs22.x

functions:
root:
handler: handler.hello
events:
- http:
path: /
method: get

plugins:
- serverless-offline

build:
esbuild:
bundle: true
minify: true
sourcemap: true
exclude: ['aws-sdk']
target: node22
platform: node
define:
SERVICE_NAME: '"my-api4-${sls:stage}"'
```

- file: handler.ts

```ts
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';

declare const SERVICE_NAME: string;

export const hello = async (
event: APIGatewayProxyEvent
): Promise => {
return {
statusCode: 200,
body: JSON.stringify(
{
message: 'Hello from root path!',
serviceName: SERVICE_NAME,
}
)
};
};
```

**Expected behavior/code**

When running serverless offline start, the constant SERVICE_NAME should be replaced correctly, and the handler should return a response like the following:

```json
{"message":"Hello from root path!","serviceName":"my-api4-dev"}
```

**Environment**

- `serverless` version: 4.14.3
- `serverless-offline` version: 14.4.0
- `esbuild` version: 0.25.3
- `node.js` version: 22.15.0
- `OS`: macOS 15.3

**Possible Solution**

N/A

**Additional context/Screenshots**

When invoking the API after running serverless offline start, the constant SERVICE_NAME is not replaced, and the following error occurs:
```
✖ Unhandled exception in handler 'root'.
✖ ReferenceError: SERVICE_NAME is not defined
at hello (/sls/ts-sls/sls-2/handler.ts:13:22)
at InProcessRunner.run (file:///sls/ts-sls/sls-2/node_modules/serverless-offline/src/lambda/handler-runner/in-process-runner/InProcessRunner.js:87:20)
at async MessagePort. (file:///sls/ts-sls/sls-2/node_modules/serverless-offline/src/lambda/handler-runner/worker-thread-runner/workerThreadHelper.js:24:14)
✖ SERVICE_NAME is not defined
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.