This project combines a Next.js frontend with a Sanity Studio for content management and automatic Algolia search indexing for powerful, real-time search functionality.
Content teams need to keep their search functionality up-to-date with their latest content, but manually syncing content to search indexes is time-consuming and error-prone. This creates a gap between published content and searchable content.
This project automatically syncs documents to Algolia's search index, ensuring your search functionality always reflects your latest content. When content is published, updated, or deleted in Sanity, the system automatically:
- Creates new search records in Algolia
- Updates existing search records with latest content
- Removes deleted content from search indexes
- Maintains real-time synchronization between content and search
- π Real-time search updates - Content becomes searchable immediately upon publishing
- β‘ Reduced manual work - No need for manual search index updates
- π― Search accuracy - Search results always reflect your latest published content
- π οΈ Simplified implementation - Automatic document synchronization with zero maintenance
- π Scalable content - Handles updates automatically as your content grows
- π Performance - Leverages Algolia's lightning-fast search infrastructure
This project consists of three main components:
- Frontend (
/frontend) - Next.js 15 app with search functionality - Studio (
/studio) - Sanity Studio for content management - Functions (
/functions) - Sanity Functions for automatic Algolia sync
- App Router for blazing-fast performance and SEO-friendly static sites
- Real-time Visual Editing with Sanity's Presentation Tool
- Live Content API for dynamic, real-time experiences
- Customizable Pages with drag-and-drop page builder
- AI-powered Media Support with auto-generated alt text
- On-demand Publishing with Incremental Static Revalidation
- Integrated Unsplash support for seamless media handling
- Real-time collaboration with team members
- Fine-grained revision history
- Visual editing with live preview
- Content validation and structured data
- Automatic sync on content publish/update/delete
- Real-time search with sub-second response times
- Node.js v22.x
- A Sanity account
- An Algolia account with:
- Application ID
- Write API key
- An index named 'posts' (or customize as needed)
# Clone the repository
git clone <your-repo-url>
cd algolia-sync-function
# Install dependencies
npm installCreate a .env file in the project root:
# Algolia Configuration
ALGOLIA_APP_ID=your_algolia_app_id
ALGOLIA_WRITE_KEY=your_algolia_write_key
SANITY_PROJECT_ID=your_sanity_projectID
SANITY_DATASET=your_dataset_name# Start both Next.js and Sanity Studio
npm run devThis will start:
- Next.js app: http://localhost:3000
- Sanity Studio: http://localhost:3333
The Algolia sync function is already configured in sanity.blueprint.ts. It automatically:
- Triggers on
create,update, anddeleteevents for post documents - Syncs document data to Algolia's search index
- Handles error cases and provides detailed logging
For existing content, run the initial sync script:
# Sync all existing posts to Algolia
npm run sync:algoliaThis script will:
- Connect to your Sanity project
- Fetch all documents of type "post"
- Transform data to match Algolia's format
- Upload all documents to the Algolia index
- Provide detailed logging of the sync process
- Open the Sanity Studio at http://localhost:3333
- Click "+ Create" and select "Post"
- Add your content with title, body, and other fields
- Publish the document
Result: The content is automatically synced to Algolia and becomes searchable immediately!
The project includes these document types:
- Page - Static pages with page builder
- Post - Blog posts and articles
- Person - Author profiles
- Settings - Site-wide configuration
- Edit content live with Sanity's Presentation Tool
- See changes in real-time on your Next.js app
- Collaborate with team members in real-time
The project includes a search component (/frontend/app/components/Search.tsx) that:
- Connects to Algolia's search API
- Provides real-time search results
- Instant search with sub-second response times
# Test with sample document
npx sanity functions test algolia-document-sync --file functions/algolia-document-sync/document.json --dataset production --with-user-token
# Test with custom data
npx sanity functions test algolia-document-sync --data '{
"_type": "post",
"_id": "test-post",
"title": "Test Article"
}' --dataset production --with-user-token
# Interactive development mode
npx sanity functions dev# Export a real document for testing
cd studio
npx sanity documents get "your-post-id" > ../test-document.json
cd ..
npx sanity functions test algolia-document-sync --file test-document.json --dataset production --with-user-tokencd studio
npx sanity deployDeploy to your preferred hosting provider (Vercel recommended):
- Create a GitHub repository
- Connect to Vercel
- Set Root Directory to
/frontend - Configure environment variables
Ensure your production environment has:
ALGOLIA_APP_IDenvironment variableALGOLIA_WRITE_KEYenvironment variable- Sanity project configuration
Update the fields synced to Algolia in functions/algolia-document-sync/index.ts:
await algolia.addOrUpdateObject({
indexName: 'posts',
objectID: _id,
body: {
title,
slug: data.slug?.current,
publishedAt: data.publishedAt,
author: data.author?.name,
// Add more fields as needed
},
})Modify the index name or sync to multiple indexes:
await algolia.addOrUpdateObject({
indexName: 'your-custom-index',
objectID: _id,
body: { title },
})Update the filter to sync specific document types:
filter: "_type == 'post' && defined(publishedAt)"Modify the search component in /frontend/app/components/Search.tsx to:
- Change search result layout
- Add custom filters
- Implement search analytics
- Customize search suggestions
- Track search queries and results
- Monitor search performance
- Understand user search behavior
- Optimize search relevance
Monitor the sync function for:
- Successful syncs
- Error handling
- Performance metrics
- Content update frequency
- Search not working: Check Algolia credentials and index configuration
- Content not syncing: Verify function deployment and environment variables
- Slow search: Check Algolia index configuration and search settings
- Missing content: Run initial sync script for existing content
Enable detailed logging in the sync function:
console.log('Event data:', JSON.stringify(event.data, null, 2))
console.log('Syncing to Algolia:', data._id)- Sanity Documentation
- Next.js Documentation
- Algolia Documentation
- Sanity Functions
- Join the Sanity Community
- Learn Sanity
- Fork the repository
- Create a feature branch
- Make your changes
- Test thoroughly
- Submit a pull request
This project is open source and available under the MIT License.
