{"id":17516,"library":"bragg-sns","title":"Bragg SNS Middleware","description":"bragg-sns is a specialized middleware designed for the `bragg` micro-framework, facilitating the processing of AWS SNS (Simple Notification Service) events as if they were conventional HTTP requests. This package abstracts the underlying SNS message structure, allowing developers to define routes for specific SNS topics using a `sns:TopicName` prefix within `bragg-router`. The core message content is then made available through `ctx.request.body`. The current stable version is 2.0.0, which notably enhanced functionality by adding support for SNS message attributes. The package integrates tightly with `bragg` and `bragg-router`, making it a suitable choice for building event-driven, serverless applications, particularly in AWS Lambda environments. It also provides topic name mapping capabilities, allowing for flexible event routing and consolidation via object or function-based transformations.","status":"active","version":"2.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/SamVerschueren/bragg-sns","tags":["javascript","bragg","framework","sns","event","middleware","aws","lambda"],"install":[{"cmd":"npm install bragg-sns","lang":"bash","label":"npm"},{"cmd":"yarn add bragg-sns","lang":"bash","label":"yarn"},{"cmd":"pnpm add bragg-sns","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core micro-framework that bragg-sns extends.","package":"bragg","optional":false},{"reason":"Provides the routing mechanism that bragg-sns integrates with for topic-based event handling.","package":"bragg-router","optional":false}],"imports":[{"note":"Package primarily uses CommonJS `require()` syntax; direct ESM `import` may require transpilation or specific Node.js configuration.","wrong":"import sns from 'bragg-sns';","symbol":"sns","correct":"const sns = require('bragg-sns');"},{"note":"The `bragg` framework is initialized as a function call immediately after requiring it.","wrong":"import bragg from 'bragg'; const app = bragg();","symbol":"app","correct":"const app = require('bragg')();"},{"note":"Similar to `bragg`, `bragg-router` is typically initialized by calling the required module.","wrong":"import router from 'bragg-router'; const router = router();","symbol":"router","correct":"const router = require('bragg-router')();"}],"quickstart":{"code":"const app = require('bragg')();\nconst router = require('bragg-router')();\nconst sns = require('bragg-sns');\n\n// Basic handler for SNS events from 'MyTopic'\nrouter.post('sns:MyTopic', ctx => {\n    console.log('Received SNS event from MyTopic:', ctx.request.body);\n    ctx.body = { status: 'Success', message: 'Event processed' };\n});\n\n// Example of topic mapping: Events from 'DevTopic' are routed to 'MyTopic' handler\napp.use(sns({\n    DevTopic: 'MyTopic'\n}));\n\n// Apply the router middleware\napp.use(router.routes());\n\n// This function can be exported as an AWS Lambda handler\nexports.handler = app.listen();\n\n// For local testing (optional, not part of typical Lambda setup)\nif (require.main === module) {\n    // Simulate an SNS event for testing\n    const simulateSnsEvent = async (topicName, message) => {\n        const context = {}; // Lambda context object\n        const event = {\n            Records: [{\n                Sns: {\n                    TopicArn: `arn:aws:sns:us-east-1:123456789012:${topicName}`,\n                    Message: JSON.stringify(message),\n                    MessageAttributes: {}\n                }\n            }]\n        };\n        console.log(`Simulating SNS event for ${topicName}...`);\n        await exports.handler(event, context);\n        console.log('Simulation complete.');\n    };\n    \n    simulateSnsEvent('MyTopic', { data: 'hello world from MyTopic' });\n    simulateSnsEvent('DevTopic', { environment: 'development', payload: 'test data' });\n}\n","lang":"javascript","description":"This quickstart demonstrates setting up `bragg` with `bragg-sns` and `bragg-router` to handle SNS events, including a simple topic mapping and local simulation for testing."},"warnings":[{"fix":"Ensure all SNS event routes are prefixed, e.g., `router.post('sns:YourTopicName', ...)`.","message":"The `sns:` prefix is mandatory when defining routes for SNS topics with `bragg-router`. Routes defined without this prefix will not be matched by `bragg-sns`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Review how `ctx.request.body` is consumed in your handlers to ensure it correctly parses messages that may now include attribute data or have a slightly altered structure due to attribute handling in v2.0.0.","message":"Version 2.0.0 introduced support for SNS message attributes. While this is an additive feature, if your application previously assumed `ctx.request.body` would *only* contain the raw SNS message, the presence of message attributes might subtly change the structure or parsing needs, particularly if message attributes are encoded within the message payload.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"For ESM projects, consider using a CommonJS wrapper, configuring your build system to handle CJS modules, or sticking to `require()` within a CJS-compatible file.","message":"This package, and the underlying `bragg` framework, are primarily designed for CommonJS (`require()`) environments. While Node.js has robust interoperability, direct usage in modern ESM (`import`) modules might require specific configurations or transpilation, potentially leading to 'require is not defined' errors.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Change the route definition from `router.post('MyTopic', ...)` to `router.post('sns:MyTopic', ...)`.","cause":"The SNS route was defined without the required 'sns:' prefix.","error":"Error: No handler found for path 'MyTopic'"},{"fix":"Ensure `app` and `router` are initialized with parentheses: `const app = require('bragg')();` and `const router = require('bragg-router')();`.","cause":"The `bragg` application instance (`app`) or `bragg-router` instance (`router`) was not correctly initialized by calling the required module as a function (e.g., `require('bragg')()` instead of `require('bragg')`).","error":"TypeError: app.use is not a function"},{"fix":"If possible, rename your file to `.cjs` or configure your `package.json` with `\"type\": \"commonjs\"`. Alternatively, use dynamic `import()` for CJS modules within ESM, or consider a bundling step.","cause":"Attempting to use `require()` syntax within an ECMAScript Module (ESM) file (e.g., a file ending in `.mjs` or when `\"type\": \"module\"` is set in `package.json`).","error":"ReferenceError: require is not defined in ES module scope"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}