In this final post, we will look at how to deploy our Next.js project to Vercel.
In the last post, we covered how to deploy our backend to Strapi Cloud and seed it with initial data.
If you missed the previous post, you can find them in the following links.
- )
Let's Create a Vercel Account.
If you don't have a Vercel account, let's go and create one.
Navigate to the following link
Now, complete the steps to create your account. I will choose the hobby plan and sign up using my GitHub account.
.
Once logged in to Strapi Cloud, navigate to your Project > Setting > Domains to see the domain in which your project is hosted.
.
Navigate to the src/lib/utils.ts file, and let's update our getStrapiUrl function from this:
export function getStrapiURL() {
return process.env.NEXT_PUBLIC_STRAPI_URL ?? "http://localhost:1337";
}
To this:
export function getStrapiURL() {
return process.env.STRAPI_URL ?? "http://localhost:1337";
}
Now let's run the following command to test our project locally.
yarn dev
➜ frontend git:(main) ✗ yarn dev
▲ Next.js 14.2.14
- Local: http://localhost:3000
- Environments: .env.local
✓ Starting...
✓ Ready in 1548ms
When you navigate the front end of your project, you will see the following error. This is normal since we did not set up our hostname for our images inside the next.config.ts file.
⨯ node_modules/next/dist/shared/lib/image-loader.js (41:26) @ defaultLoader
⨯ Error: Invalid src prop (https://timely-joy-94aadb93be.media.strapiapp.com/ee53b3ce_4520_45da_a243_6c83f88de744_e9d2a1dc41.png) on `next/image`, hostname "timely-joy-94aadb93be.media.strapiapp.com" is not configured under images in your `next.config.js`
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host
at Array.map (<anonymous>)
Excellent, it worked locally. Now, navigate to your Strapi CMS Admin on Strapi Cloud. You should see the newly created summary in your deployed Strapi project.
Let's set up our project to use the Next.js as the framework preset and Root Directory to point to our project in the frontend folder.
After you add the following environmental variable, you can click the deploy button to deploy your project.
Once you update the environment variable and redeploy, you should be able to log in and see your secure httpOnly cookies being set.
awesome in-depth video by Lee Robinson on the topic.
Dealing With Function Invocation Timeout
When building your Next.js application, keep this in mind. Different environments come with different caveats.
In our case, our summarize function takes more than 10 seconds to summarize a video. If you are using a hobby plan, this will trigger the FUNCTION_INVOCATION_TIMEOUT error.
. But in my case, it was because, on a hobby plan, you only get 10s execution time for functions.
.
After upgrading to the pro plan, I could increase the runtime limit in my app with the following change in the src/app/api/summarize/route.ts file.
export const maxDuration = 150;
export const dynamic = "force-dynamic";
The completed file looks like the following.
import { NextRequest } from "next/server";
import { ChatOpenAI } from "@langchain/openai";
import { PromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
import { fetchTranscript } from "@/lib/youtube-transcript";
import { getUserMeLoader } from "@/data/services/get-user-me-loader";
import { getAuthToken } from "@/data/services/get-token";
export const maxDuration = 150;
export const dynamic = "force-dynamic";
function transformData(data: any[]) {
let text = "";
data.forEach((item) => {
text += item.text + " ";
});
return {
data: data,
text: text.trim(),
};
}
const TEMPLATE = `
INSTRUCTIONS:
For the this {text} complete the following steps.
Generate the title based on the content provided
Summarize the following content and include 5 key topics, writing in first person using normal tone of voice.
Write a youtube video description
- Include heading and sections.
- Incorporate keywords and key takeaways
Generate bulleted list of key points and benefits
Return possible and best recommended key words
`;
async function generateSummary(content: string, template: string) {
const prompt = PromptTemplate.fromTemplate(template);
const model = new ChatOpenAI({
openAIApiKey: process.env.OPENAI_API_KEY,
modelName: process.env.OPENAI_MODEL ?? "gpt-4-turbo-preview",
temperature: process.env.OPENAI_TEMPERATURE
? parseFloat(process.env.OPENAI_TEMPERATURE)
: 0.7,
maxTokens: process.env.OPENAI_MAX_TOKENS
? parseInt(process.env.OPENAI_MAX_TOKENS)
: 4000,
});
const outputParser = new StringOutputParser();
const chain = prompt.pipe(model).pipe(outputParser);
try {
const summary = await chain.invoke({ text: content });
return summary;
} catch (error) {
if (error instanceof Error)
return new Response(JSON.stringify({ error: error.message }));
return new Response(
JSON.stringify({ error: "Failed to generate summary." })
);
}
}
export async function POST(req: NextRequest) {
console.log("FROM OUR ROUTE HANDLER:", req.body);
const user = await getUserMeLoader();
const token = await getAuthToken();
if (!user.ok || !token)
return new Response(
JSON.stringify({ data: null, error: "Not authenticated" }),
{ status: 401 }
);
if (user.data.credits < 1)
return new Response(
JSON.stringify({
data: null,
error: "Insufficient credits",
}),
{ status: 402 }
);
const body = await req.json();
const { videoId } = body;
let transcript: Awaited<ReturnType<typeof fetchTranscript>>;
try {
transcript = await fetchTranscript(videoId);
const transformedData = transformData(transcript);
console.log("Transcript:", transformedData.text);
let summary: Awaited<ReturnType<typeof generateSummary>>;
summary = await generateSummary(transformedData.text, TEMPLATE);
console.log("Summary:", summary);
return new Response(JSON.stringify({ data: summary, error: null }));
} catch (error) {
console.error("Error processing request:", error);
if (error instanceof Error)
return new Response(JSON.stringify({ error: error }));
return new Response(JSON.stringify({ error: "Unknown error" }));
}
}
Once you make the change, save your changes to GitHub and redeploy.
Let's try this again.
. Next.js also has an AI SDK that simplifies working with AI and LLMs. You can learn more about it for our daily "open office hours" from 12:30 PM CST to 1:30 PM CST.
If you have a suggestion or find a mistake in the post, please open an issue on the .
Feel free to make PRs to fix any issues you find in the project, or let me know if you have any questions.
Happy coding!
- Paul
SOCIAL SHARE CARD GENERATOR