4 min read
•Question 57 of 62hardHow to build serverless functions with Node.js?
AWS Lambda and serverless architecture.
What You'll Learn
- Serverless concepts
- AWS Lambda functions
- Serverless Framework
AWS Lambda Handler
code.jsJavaScript
// handler.js
exports.hello = async (event) => {
const name = event.queryStringParameters?.name || 'World';
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: `Hello, ${name}!` })
};
};
exports.createUser = async (event) => {
const body = JSON.parse(event.body);
// Process user creation
const user = await saveUser(body);
return {
statusCode: 201,
body: JSON.stringify(user)
};
};Serverless Framework
$ terminalBash
npm install -g serverlessconfig.ymlYAML
# serverless.yml
service: my-api
provider:
name: aws
runtime: nodejs20.x
region: us-east-1
functions:
hello:
handler: handler.hello
events:
- http:
path: /hello
method: get
createUser:
handler: handler.createUser
events:
- http:
path: /users
method: post$ terminalBash
# Deploy
serverless deploy
# Test locally
serverless invoke local -f helloBest Practices
code.jsJavaScript
// Keep functions small and focused
// Initialize outside handler (reused between invocations)
const db = require('./db');
exports.handler = async (event) => {
// Use existing connection
return await db.query('SELECT * FROM users');
};