Modern web applications demand performance, scalability, and increasingly, intelligent features. Integrating diverse technologies like Hapi.js for the backend, Server-Side Rendering (SSR) for initial load speed, the Cohere API for AI capabilities, and Docker Cloud for seamless deployment, all powered by TypeScript, creates a powerful and maintainable stack.
The Integrated Architecture
Our architecture centers around a Hapi.js server acting as the orchestrator. It handles incoming requests, fetches data, interacts with the Cohere API for AI-driven content, and renders the initial HTML using SSR before sending it to the client. Docker Cloud provides the infrastructure to build, deploy, and scale this containerized application efficiently.
Building the Hapi.js Backend with TypeScript
Hapi.js provides a powerful framework for building scalable and robust API servers and web applications. Its plugin architecture and comprehensive ecosystem make it ideal for complex projects.
First, set up your Hapi project with TypeScript:
// src/server.ts
import Hapi from '@hapi/hapi';
import { Server } from '@hapi/hapi';
import { renderPage } from './ssr/renderer'; // We'll create this next
import { generateAIContent } from './plugins/cohere'; // And this one
const init = async () => {
const server: Server = Hapi.server({
port: process.env.PORT || 3000,
host: '0.0.0.0'
});
// Serve static files (e.g., CSS, client-side JS)
await server.register(require('@hapi/inert'));
server.route({
method: 'GET',
path: '/static/{param*}',
handler: { directory: { path: 'public' } }
});
server.route({
method: 'GET',
path: '/',
handler: async (request, h) => {
const aiPrompt = 'Write a compelling headline for an article about full-stack AI.';
const aiHeadline = await generateAIContent(aiPrompt);
const content = `<h1>${aiHeadline}</h1><p>Welcome to our AI-powered application!</p>`;
return h.response(renderPage('Home', content)).type('text/html');
}
});
await server.start();
console.log(`Server running on ${server.info.uri}`);
};
process.on('unhandledRejection', (err) => {
console.error(err);
process.exit(1);
});
init();
Server-Side Rendering for Performance
SSR is crucial for initial page load performance, SEO, and accessibility, as the browser receives a fully formed HTML document. For simplicity, we'll use a basic template string.
// src/ssr/renderer.ts
export const renderPage = (title: string, content: string): string => {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${title}</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div id="app">
${content}
</div>
<script src="/static/client.js"></script>
</body>
</html>
`;
};
Integrating the Cohere API
The Cohere API provides powerful language AI models for tasks like text generation, embeddings, and summarization. Integrating it allows your application to offer dynamic, AI-driven content.
Sign up for a Cohere API key here.
// src/plugins/cohere.ts
import { CohereClient } from 'cohere-ai';
const cohere = new CohereClient({
token: process.env.COHERE_API_KEY || 'YOUR_COHERE_API_KEY', // Use environment variables!
});
export const generateAIContent = async (prompt: string): Promise<string> => {
try {
const response = await cohere.generate({
prompt: prompt,
maxTokens: 50,
temperature: 0.9,
model: 'command'
});
return response.generations[0].text.trim();
} catch (error) {
console.error('Error calling Cohere API:', error);
return 'Failed to generate AI content.';
}
};
Containerization with Docker Cloud
Docker Cloud (now integrated into Docker Hub and Docker Desktop with CI/CD features) streamlines the process of building, deploying, and managing containerized applications. It ensures consistency across environments and simplifies scaling.
Create a Dockerfile at the root of your project:
# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --omit=dev
COPY . .
RUN npm run build
ENV NODE_ENV=production
EXPOSE 3000
CMD [ "node", "dist/server.js" ]
This Dockerfile builds your TypeScript application, installs dependencies, and sets up the production environment. You would then push this image to Docker Hub, and configure Docker Cloud (or a similar CI/CD service like GitHub Actions with Docker integration) to deploy and manage instances of your application.
Conclusion
By meticulously integrating Hapi.js, Server-Side Rendering, the Cohere API, and Docker Cloud with TypeScript, we've crafted a robust, intelligent, and deployable full-stack application. This approach not only leverages the strengths of each technology but also provides a scalable and maintainable foundation for future development. Experiment with more complex AI interactions and advanced SSR techniques to further enhance your application's capabilities.