DynamoDB PutItem in Node.js (AWS SDK v3)
PutItem writes a whole item, creating it or replacing any existing item with the same primary key. In AWS SDK v3 you send a PutItemCommand whose Item holds every attribute in low-level format ({ S: ... }, { N: ... }).
Code
import {DynamoDBClient, PutItemCommand} from '@aws-sdk/client-dynamodb';
const client = new DynamoDBClient({region: 'us-east-1'});
async function addSong() {
const command = new PutItemCommand({
TableName: 'Music',
Item: {
Artist: {S: 'Arturo Sandoval'},
SongTitle: {S: 'Cubano Chant'},
AlbumTitle: {S: 'Danzon'},
Year: {N: '1994'},
Awards: {N: '0'}
},
// Only write if no item with this key already exists
ConditionExpression: 'attribute_not_exists(Artist) AND attribute_not_exists(SongTitle)'
});
try {
await client.send(command);
console.log('Song written');
} catch (err) {
if (err.name === 'ConditionalCheckFailedException') {
console.log('A song with that key already exists — not overwritten');
} else {
throw err;
}
}
}
addSong();Explanation
Item— must contain the table's full primary key, plus any other attributes. Numbers are strings under theNtype ({ N: "1994" }).- Put replaces — without a condition,
PutItemsilently overwrites an existing item with the same key. UseUpdateItemto change a few attributes without clobbering the rest. ConditionExpression—attribute_not_exists(<key>)makes the write a create-only insert; the write fails withConditionalCheckFailedExceptionif the item already exists. This is DynamoDB's optimistic-locking primitive.- To get the overwritten item back, add
ReturnValues: "ALL_OLD". - Prefer the
DynamoDBDocumentClient(@aws-sdk/lib-dynamodb) if you'd rather pass plain JS objects than typed attribute values.
Do it visually
Writing a conditional put by hand? The DynamoDB Expression Builder assembles the ConditionExpression and copies the code.
To add and edit items in a GUI — a form per attribute, type pickers, and copy-as-code — download DynoTable.
Related guides
- DynamoDB condition expressions —
attribute_not_exists, optimistic locking, and more. - DynamoDB data types — how each attribute type is written.