<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Osama Ayub on Medium]]></title>
        <description><![CDATA[Stories by Osama Ayub on Medium]]></description>
        <link>https://medium.com/@ayubosama416?source=rss-97e019f2e7c3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xwbCTqeEJXTJtDF9QFGsRA.jpeg</url>
            <title>Stories by Osama Ayub on Medium</title>
            <link>https://medium.com/@ayubosama416?source=rss-97e019f2e7c3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 20:04:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayubosama416/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Writing API Routes for Forms in Next.js 16: Server Actions Done Right]]></title>
            <link>https://medium.com/@ayubosama416/stop-writing-api-routes-for-forms-in-next-js-16-server-actions-done-right-93aa2bbe7187?source=rss-97e019f2e7c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/93aa2bbe7187</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Osama Ayub]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 15:29:55 GMT</pubDate>
            <atom:updated>2026-11-15T15:29:55.327Z</atom:updated>
            <content:encoded><![CDATA[<h4>Zod validation, errors that keep what the user typed, a pending button, and the one transaction that stops users from going over your limits.</h4><p>Type too little and you get a clear error, and your text is still there. Paste real meeting notes and the AI writes a summary with action items. This form has no API route and no fetch call. It’s a Next.js Server Action, and this is the pattern I use for every form.</p><p>Watch the build: <a href="https://youtu.be/qJlbSqavw_E">https://youtu.be/qJlbSqavw_E</a></p><p>Free source code (AI SaaS starter): <a href="https://github.com/osamaayub/briefai">https://github.com/osamaayub/briefai</a></p><h3>The old way vs Server Actions</h3><p>The old way needs an API route, a fetch call, JSON parsing, and three pieces of state for loading, errors and data. With a Server Action, you write one function on the server and the form calls it directly. React gives you the loading state and the result.</p><p>The flow: the form sends form data, the action runs on the server, Zod checks the input, the action returns an error or success, and useActionState re-renders the form with that result.</p><h3>Step 1: One schema for the rules</h3><p>Error messages are written for users, not developers. The limits are exported, so the textarea uses the same max length. One source of truth.</p><pre>export const NOTES_MIN = 30;<br>export const NOTES_MAX = 6000;<br><br>export const NotesSchema = z.string().trim()<br>  .min(NOTES_MIN, &quot;Paste at least a few sentences of notes&quot;)<br>  .max(NOTES_MAX, &quot;Notes are too long (max 6,000 characters)&quot;);</pre><h3>Step 2: The Server Action</h3><p>Get the user on the server. Never trust a user ID sent from the browser. On failure, return the error and also the notes the user typed. That is the detail most tutorials miss.</p><pre>&quot;use server&quot;;<br><br>export async function generateBrief(_: State, formData: FormData) {<br>  const user = await getCurrentUser(); // never trust the client<br>  const notes = String(formData.get(&quot;notes&quot;) ?? &quot;&quot;);<br><br>  const result = await briefService().generate(user.id, notes);<br>  if (!result.ok)<br>    return { status: &quot;error&quot;, message: result.message, fields: { notes } };<br><br>  refresh();<br>  return { status: &quot;success&quot; };<br>}</pre><h3>Step 3: useActionState in the form</h3><p>You get the last result, a form action and a pending flag. The returned notes go back in as the textarea’s default value, so nobody has to retype a long message after an error. The submit button is disabled while the action runs and says “Thinking…”, so nobody submits twice.</p><pre>const [state, action, pending] = useActionState(generateBrief, { status: &quot;idle&quot; });<br>const notes = state.status === &quot;error&quot; ? state.fields?.notes : undefined;<br><br>&lt;form action={action}&gt;<br>  &lt;textarea name=&quot;notes&quot; maxLength={NOTES_MAX} defaultValue={notes} /&gt;<br>  {state.status === &quot;error&quot; &amp;&amp; &lt;FormError message={state.message} /&gt;}<br>  &lt;SubmitButton pending={pending}&gt;Generate brief&lt;/SubmitButton&gt;<br>&lt;/form&gt;</pre><h3>The line that enforces your limits</h3><p>A Server Action is a public endpoint. Anyone can call it with any data, even without your form. So every action checks the user, validates the input, enforces limits on the server, and returns friendly errors instead of crashing.</p><p>If you check the limit and insert later, two requests at the same moment can both pass the check, and the free plan gets six briefs instead of five. Count and insert inside one transaction, and even a script sending ten requests at once can’t go over.</p><pre>insertWithinLimit(data, limit, since) {<br>  return db().transaction(async (tx) =&gt; {<br>    const [row] = await tx.select({ n: count() })<br>      .from(briefs).where(ownedSince(data.userId, since));<br>    if (row.n &gt;= limit) return null;<br>    const [created] = await tx.insert(briefs).values(data).returning();<br>    return created;<br>  }, { behavior: &quot;immediate&quot; });<br>}</pre><h3>Your turn</h3><p>Challenge: add an Undo button after deleting a brief, using useOptimistic. Then watch the full AI SaaS build: <a href="https://youtu.be/AlgmQzrKSTk">https://youtu.be/AlgmQzrKSTk</a></p><p>New full-stack and AI builds every week on my YouTube channel: <a href="https://www.youtube.com/@osamaayubdev">https://www.youtube.com/@osamaayubdev</a></p><p>I’m Osama Ayub, a full-stack developer building Next.js and AI apps. The videos use an AI-generated voiceover; the code and screen recordings are from my own projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93aa2bbe7187" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add GitHub and Google Login to Next.js 16 with Auth.js (Plus the Redirect Bug Most Tutorials Miss)]]></title>
            <link>https://medium.com/@ayubosama416/add-github-and-google-login-to-next-js-16-with-auth-js-plus-the-redirect-bug-most-tutorials-miss-ef3749217039?source=rss-97e019f2e7c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef3749217039</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Osama Ayub]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 15:23:28 GMT</pubDate>
            <atom:updated>2026-11-15T15:23:28.748Z</atom:updated>
            <content:encoded><![CDATA[<h4>OAuth, email and password, rate limits, and a small fix that stops attackers from phishing your users. Real code from a live app.</h4><p>This sign-in page has GitHub, Google, and email with a password. Wrong passwords get a clear error, and the sign-up form checks your password as you type. It is the real sign-in from my free course platform, and in this post you’ll build the same thing with Next.js 16 and Auth.js (NextAuth v5).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQ8eE5bxZEkA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQ8eE5bxZEkA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQ8eE5bxZEkA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4e1cb8d5669e61fa19ced040b23f616/href">https://medium.com/media/d4e1cb8d5669e61fa19ced040b23f616/href</a></iframe><p>Free source code: <a href="https://github.com/osamaayub/webdev-path-lms">https://github.com/osamaayub/webdev-path-lms</a></p><h3>How “Sign in with GitHub” actually works</h3><p>Your app sends the user to GitHub. GitHub asks if they allow your app. GitHub sends the user back to your callback URL with a one-time code. Auth.js swaps that code for the user’s profile on the server, saves the user, and sets a signed session cookie. You never see their GitHub password.</p><p>To set it up, create an OAuth app in GitHub (Settings, then Developer settings). In development the callback URL must be exactly localhost:3000/api/auth/callback/github. Google works the same way in the Google Cloud console. Make separate OAuth apps for development and production, because the callback URLs differ.</p><h3>Step 1: Environment variables</h3><p>Auth.js picks up these exact names automatically, so you don’t pass them in code. Never commit this file.</p><pre># npx auth secret  (makes a long random value)<br>AUTH_SECRET=your-random-secret<br>AUTH_GITHUB_ID=your-github-client-id<br>AUTH_GITHUB_SECRET=your-github-client-secret<br>AUTH_GOOGLE_ID=your-google-client-id<br>AUTH_GOOGLE_SECRET=your-google-client-secret<br>DATABASE_URL=postgres://...</pre><h3>Step 2: Configure Auth.js</h3><p>The Drizzle adapter saves users and their linked accounts in Postgres. JWT sessions mean checking who is signed in doesn’t need a database read on every request. A single catch-all route (app/api/auth/[…nextauth]/route.ts exporting GET and POST from handlers) then takes care of redirects, callbacks and sign-out.</p><pre>export const { handlers, auth, signIn, signOut } = NextAuth({<br>  adapter: DrizzleAdapter(db, { usersTable: users, accountsTable: accounts }),<br>  providers: [GitHub, Google],<br>  session: { strategy: &quot;jwt&quot; },<br>  pages: { signIn: &quot;/sign-in&quot; },<br>});</pre><h3>Step 3: Sign-in buttons as a Server Action</h3><p>The buttons are plain forms, so they work even before the page’s JavaScript loads. The action only accepts providers we allow. Notice safeReturn; we’ll come back to it.</p><pre>&quot;use server&quot;;<br><br>export async function signInWith(form: FormData) {<br>  const provider = form.get(&quot;provider&quot;);<br>  if (provider !== &quot;github&quot; &amp;&amp; provider !== &quot;google&quot;) return;<br>  const redirectTo = safeReturn(form.get(&quot;returnTo&quot;));<br>  await signIn(provider, { redirectTo });<br>}</pre><h3>Step 4: Email and password, the safe way</h3><p>Before checking the password, count recent failed attempts for that email and block guessing. A wrong email and a wrong password return the same error, so attackers can’t find out which emails have accounts. Passwords are hashed with scrypt, which is built into Node, with a random salt per password and a constant-time comparison (timingSafeEqual), so the response time leaks nothing.</p><pre>Credentials({<br>  id: &quot;password&quot;,<br>  async authorize(input) {<br>    const email = String(input?.email ?? &quot;&quot;).toLowerCase();<br>    const key = `signin:${email}`;<br>    if (await tooManyAttempts(key)) throw new TooManyAttempts();<br>    const user = await checkPassword(email, input.password);<br>    if (!user) { await recordAttempt(key); return null; }<br>    await clearAttempts(key);<br>    return user;<br>  },<br>})</pre><h3>The redirect bug</h3><p>Many apps send users back where they came from after sign-in, using a returnTo value in the URL. If you don’t check it, an attacker sends a link with returnTo set to their own site. The user signs in on your real site, then lands on a perfect fake copy that asks for their password again.</p><p>The fix is small: only allow paths that start with one slash, never two, because the browser treats //evil.com as another site. That is what safeReturn does before every redirect.</p><h3>Who can be an admin?</h3><p>Admins are listed by email in an environment variable. But anyone can sign up with a password using your admin email, because email sign-up doesn’t prove you own the inbox. So the session remembers how the user signed in, and only GitHub or Google sessions can be admin.</p><pre>callbacks: {<br>  jwt({ token, user, account }) {<br>    if (user?.id) token.sub = user.id;<br>    if (account) token.method = account.provider; // HOW they signed in<br>    return token;<br>  },<br>}<br><br>// admin = listed email AND a verified provider<br>const admin = isAdminEmail(email) &amp;&amp; method !== &quot;password&quot;;</pre><h3>Launch checklist</h3><ul><li>A long random AUTH_SECRET.</li><li>The exact callback URL for every environment, including your live domain.</li><li>One error message for every sign-in failure.</li><li>Rate limits on password sign-in and sign-up.</li></ul><h3>Your turn</h3><p>Challenge: add a “Sign in with Discord” button. It is one more provider and two variables. The live sign-in page is linked in the GitHub README if you want to try it first.</p><p>New full-stack and AI builds every week on my YouTube channel: <a href="https://www.youtube.com/@osamaayubdev">https://www.youtube.com/@osamaayubdev</a></p><p>I’m Osama Ayub, a full-stack developer building Next.js and AI apps. The videos use an AI-generated voiceover; the code and screen recordings are from my own projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef3749217039" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Real Admin Dashboard in Next.js 16 with PostgreSQL (Not Fake Data)]]></title>
            <link>https://medium.com/@ayubosama416/build-a-real-admin-dashboard-in-next-js-16-with-postgresql-not-fake-data-980d79a2ef1b?source=rss-97e019f2e7c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/980d79a2ef1b</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Osama Ayub]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 15:18:18 GMT</pubDate>
            <atom:updated>2026-11-15T15:18:18.828Z</atom:updated>
            <content:encoded><![CDATA[<h4>KPI cards that compare periods, a revenue chart with no gaps, and an orders table with search, filters and pagination done in SQL. Free code.</h4><p>Admin dashboards are one of the most common things clients ask a full-stack developer for. Most tutorials build them on fake JSON. This one runs on a real PostgreSQL database: switch the date range and every number updates, each one compared with the period before.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVS5ceHq3CNg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVS5ceHq3CNg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVS5ceHq3CNg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/230f296e18b4e844c2c59364d02a3395/href">https://medium.com/media/230f296e18b4e844c2c59364d02a3395/href</a></iframe><p>Free source code: <a href="https://github.com/osamaayub/pulse-dashboard">https://github.com/osamaayub/pulse-dashboard</a></p><h3>What makes a dashboard useful</h3><p>Four things. It shows key numbers and compares each with the last period, because a number alone means nothing. It shows trends in a chart. It gives a searchable table for the details. And it lets you act, like marking an order as shipped, without leaving the page.</p><p>The architecture is simple: everything the user picks lives in the URL. The server parses those values with Zod, a Server Component runs the queries, Postgres does the filtering, sorting and counting, and the browser gets finished HTML plus two small chart components. That is why the page loads fast.</p><h3>Step 1: Design the tables</h3><p>Two details matter. Money is stored as whole cents, so totals never pick up rounding errors. And there are indexes on the date and status columns, because those are exactly what the dashboard filters by.</p><pre>export const orders = pgTable(&quot;orders&quot;, {<br>  id: serial(&quot;id&quot;).primaryKey(),<br>  customerId: integer(&quot;customer_id&quot;).notNull().references(() =&gt; customers.id),<br>  status: orderStatus(&quot;status&quot;).notNull(),<br>  totalCents: integer(&quot;total_cents&quot;).notNull(),<br>  createdAt: timestamp(&quot;created_at&quot;).notNull(),<br>}, (t) =&gt; [<br>  index(&quot;orders_created_idx&quot;).on(t.createdAt),<br>  index(&quot;orders_status_idx&quot;).on(t.status),<br>]);</pre><h3>Step 2: Treat the URL like user input</h3><p>Here is a bug almost every dashboard has: it trusts the URL. Change page to -3 and the query breaks. Change the range to something random and the page crashes. With a Zod schema and .catch(), a bad link quietly falls back to a safe default instead.</p><pre>const one = (v: unknown) =&gt; (Array.isArray(v) ? v[0] : v);<br><br>export const ordersQuerySchema = z.object({<br>  q: z.preprocess(one, z.string().trim().max(60).catch(&quot;&quot;)),<br>  status: z.preprocess(one, z.enum(STATUSES).optional().catch(undefined)),<br>  page: z.preprocess(one, z.coerce.number().int().min(1).max(500).catch(1)),<br>});</pre><h3>Step 3: KPIs in one query, two periods at once</h3><p>Refunded orders don’t count as revenue. The same function runs for this period and the one before, in parallel with Promise.all, and the percentage change is just the difference between the two.</p><pre>const revenue = sql&lt;number&gt;`coalesce(sum(${orders.totalCents})<br>  filter (where ${orders.status} &lt;&gt; &#39;refunded&#39;), 0)`;<br><br>const [cur, prev] = await Promise.all([<br>  windowStats(start, end), windowStats(prevStart, start)]);</pre><h3>Step 4: A revenue chart with no holes</h3><p>Postgres groups orders with date_trunc: days for short ranges, weeks for 90 days, months for a year, so the chart never has too many points. Then empty buckets are filled with zero. Without that, a day with no orders simply disappears and the line looks wrong.</p><p>Only the chart component runs in the browser (“use client”, because Recharts needs it). The data still comes from the server as a prop. That is the rule I follow: only the parts that need interaction run in the browser.</p><h3>Step 5: Search, filter, sort and paginate in SQL</h3><p>The search term is escaped, so a % typed in the box can’t act as a wildcard. Each filter adds to one where clause, and filters that aren’t set are skipped. Limit and offset give the page, so the browser only ever receives twelve rows.</p><pre>const where = and(<br>  q.status ? eq(orders.status, q.status) : undefined,<br>  term ? or(ilike(customers.name, term), ilike(customers.email, term)) : undefined,<br>);<br><br>const rows = await db.select(cols).from(orders)<br>  .innerJoin(customers, eq(orders.customerId, customers.id))<br>  .where(where)<br>  .limit(PAGE_SIZE)<br>  .offset((q.page - 1) * PAGE_SIZE);</pre><h3>The trick: the URL is the state</h3><p>The search box doesn’t keep results in React state. It waits 300 ms after you stop typing and writes the search into the URL. The server reads the URL and sends the new rows. A refresh keeps your view, the back button works, and you can send a teammate a link that opens the exact same filtered table.</p><pre>useEffect(() =&gt; {<br>  const t = setTimeout(() =&gt; {<br>    const next = new URLSearchParams(params);<br>    if (value) next.set(&quot;q&quot;, value); else next.delete(&quot;q&quot;);<br>    next.delete(&quot;page&quot;);<br>    start(() =&gt; router.replace(`${path}?${next}`));<br>  }, 300);<br>  return () =&gt; clearTimeout(t);<br>}, [value]);</pre><h3>Step 6: Ship an order safely with a Server Action</h3><p>The update only changes orders whose status is still “paid”. That check sits inside the update itself, so a double click finds nothing to change the second time. No race condition, and no order shipped twice.</p><pre>const updated = await db.update(orders)<br>  .set({ status: &quot;shipped&quot; })<br>  .where(and(eq(orders.id, id.data), eq(orders.status, &quot;paid&quot;)))<br>  .returning({ id: orders.id });</pre><h3>Before you hand it to a client</h3><ul><li>Parse every input and send security headers.</li><li>Run queries in parallel, so the slowest one sets the speed.</li><li>Block spreadsheet formulas in the CSV export, so a customer named “=something” can’t run code in Excel.</li><li>Write tests for the logic that is easy to break.</li></ul><h3>Your turn</h3><p>Challenge: add a Customers page with lifetime value per customer. Post your repo in the YouTube comments and I’ll reply to every one.</p><p>The live demo link is in the GitHub README. New full-stack and AI builds every week on my YouTube channel: <a href="https://www.youtube.com/@osamaayubdev">https://www.youtube.com/@osamaayubdev</a></p><p>I’m Osama Ayub, a full-stack developer building Next.js and AI apps. The videos use an AI-generated voiceover; the code and screen recordings are from my own projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=980d79a2ef1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a ChatGPT for Your PDFs with Next.js and RAG (and It Says “I Don’t Know”)]]></title>
            <link>https://medium.com/@ayubosama416/i-built-a-chatgpt-for-your-pdfs-with-next-js-and-rag-and-it-says-i-dont-know-79f6d6538983?source=rss-97e019f2e7c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/79f6d6538983</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Osama Ayub]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 15:12:04 GMT</pubDate>
            <atom:updated>2026-11-15T15:12:04.559Z</atom:updated>
            <content:encoded><![CDATA[<h4>Upload any PDF, ask a question, and get an answer with the exact page it came from. Step by step, with free code.</h4><p>I uploaded an employee handbook and asked, “How many vacation days do I get?” Two seconds later: 25 days, page 2.</p><p>Then I asked something the handbook does not cover. Instead of making something up, it said: “I don’t know. That isn’t in this document.”</p><p>That second answer is the one that matters. Most AI chatbots will happily invent an answer. In this post I’ll show you how to build one that doesn’t, with Next.js 16, OpenAI and a technique called RAG.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqbC_mh7XlS4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqbC_mh7XlS4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqbC_mh7XlS4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7484a44e6b7e54ff8c18b16dedfa3caa/href">https://medium.com/media/7484a44e6b7e54ff8c18b16dedfa3caa/href</a></iframe><p>Try it live: the free demo link (no sign-up) is at the top of the GitHub README.</p><p>Free source code: <a href="https://github.com/osamaayub/pdf-chat-ai">https://github.com/osamaayub/pdf-chat-ai</a></p><h3>Why not paste the whole PDF into ChatGPT?</h3><p>There are four problems with that. Long documents hit the model’s size limit. Sending the whole document with every question costs more each time. The model mixes in its own guesses. And you can’t easily check where an answer came from.</p><p>RAG (retrieval-augmented generation) fixes all four. It works in four steps:</p><ol><li>Split the PDF into small chunks.</li><li>Turn each chunk into a vector, a list of numbers that captures its meaning.</li><li>When a question comes in, find the chunks closest to it.</li><li>Send only those chunks to the model, with strict rules.</li></ol><p>The stack is small: Next.js 16 for the page and API routes, unpdf to read the PDF, the OpenAI SDK for embeddings and answers, and Zod to validate every request.</p><h3>Step 1: Create the project</h3><pre>npx create-next-app@latest pdf-chat-ai<br>cd pdf-chat-ai<br>npm i openai unpdf zod<br><br># .env.local (never commit this file)<br>OPENAI_API_KEY=sk-...your key...</pre><h3>Step 2: Read the PDF page by page</h3><p>The upload route rejects anything that is not a PDF. The key detail is mergePages: false. We keep the text page by page, so every chunk knows which page it came from. That is what makes source pages possible later.</p><pre>export async function POST(req: Request) {<br>  const form = await req.formData();<br>  const file = form.get(&quot;file&quot;);<br>  if (!(file instanceof File) || file.type !== &quot;application/pdf&quot;)<br>    return Response.json({ error: &quot;Upload a PDF file.&quot; }, { status: 400 });<br><br>  const pdf = await getDocumentProxy(new Uint8Array(await file.arrayBuffer()));<br>  const { text } = await extractText(pdf, { mergePages: false });<br>  const pages = text.map((t, i) =&gt; ({ page: i + 1, text: t }));</pre><h3>Step 3: Split into overlapping chunks</h3><p>Each chunk is about 800 characters and ends on a full stop when it can, so sentences stay whole. Each new chunk starts 150 characters before the last one ended. That overlap means an answer sitting on the border between two chunks is still found.</p><pre>export function splitIntoChunks(pages: Page[], size = 800, overlap = 150) {<br>  const chunks: Chunk[] = [];<br>  for (const { page, text } of pages) {<br>    let start = 0;<br>    while (start &lt; text.length) {<br>      let end = Math.min(start + size, text.length);<br>      const dot = text.lastIndexOf(&quot;. &quot;, end);<br>      if (dot &gt; start + size / 2) end = dot + 1;<br>      chunks.push({ id: chunks.length, page, text: text.slice(start, end) });<br>      if (end &gt;= text.length) break;<br>      start = end - overlap;<br>    }<br>  }<br>  return chunks;<br>}</pre><h3>Step 4: Turn chunks into vectors</h3><p>All chunks go to text-embedding-3-small in one call. Texts with a similar meaning get vectors that point in a similar direction, and cosine similarity measures that.</p><pre>export async function embed(texts: string[]) {<br>  const res = await openai().embeddings.create({<br>    model: &quot;text-embedding-3-small&quot;,<br>    input: texts,<br>  });<br>  return res.data.map((d) =&gt; d.embedding);<br>}<br><br>export const cosine = (a: number[], b: number[]) =&gt;<br>  a.reduce((s, x, i) =&gt; s + x * b[i], 0);</pre><h3>Step 5: Find the best chunks</h3><p>Embed the question, score every chunk against it, and keep the top four. For this tutorial the vectors live in memory. In a real app, store them in Postgres with pgvector and let the database find the nearest ones.</p><pre>export function topChunks(doc: Doc, q: number[], k = 4) {<br>  return doc.chunks<br>    .map((c) =&gt; ({ ...c, score: cosine(c.vector, q) }))<br>    .sort((a, b) =&gt; b.score - a.score)<br>    .slice(0, k);<br>}</pre><h3>Step 6: The prompt that stops made-up answers</h3><p>This is where most chatbots go wrong. Tell the model to use only the context, give it an exact sentence for “not found”, and ask it to cite pages. Temperature 0 keeps the answers steady.</p><pre>export const SYSTEM_PROMPT = `You answer questions about one document.<br>Use ONLY the context below. If the answer is not in the context,<br>reply exactly: &quot;I don&#39;t know. That isn&#39;t in this document.&quot;<br>Keep answers short and cite pages like (page 2).`;<br><br>const stream = await openai().chat.completions.create({<br>  model: &quot;gpt-4.1-mini&quot;, stream: true, temperature: 0,<br>  messages: [<br>    { role: &quot;system&quot;, content: SYSTEM_PROMPT + &quot;\n\nContext:\n&quot; + context },<br>    { role: &quot;user&quot;, content: question },<br>  ],<br>});</pre><h3>Step 7: Stream the answer and show the source pages</h3><p>The chat component reads the response stream piece by piece, so the user watches the answer being written. When it finishes, every “(page N)” in the answer becomes a green source tag the user can check.</p><h3>Why embeddings beat keyword search</h3><p>The live demo can run without an API key, using keyword search instead. Ask it “Does the studio pay for internet?” and keyword search picks a sentence about the studio paying for a co-working space, because it shares the words “studio” and “pay”. The right answer, internet covered up to $50 a month, is on the same page.</p><p>Keyword search matches words. Embeddings match meaning. That is what you pay for.</p><h3>Before you put it in front of real users</h3><ul><li>Store vectors in Postgres with pgvector, so they survive a restart.</li><li>Add login, so each user has their own documents.</li><li>Add usage limits, and set a monthly spending cap with your AI provider.</li><li>Add OCR, because scanned PDFs are images with no text to read.</li></ul><h3>Your turn</h3><p>Challenge: make it chat with two PDFs at once. The code works with OpenAI or Claude, so use whichever key you have.</p><p>New full-stack and AI builds every week: <a href="https://www.youtube.com/@osamaayubdev">https://www.youtube.com/@osamaayubdev</a></p><p>Free 24-week web dev course: linked on my YouTube channel page.</p><p>I’m Osama Ayub, a full-stack developer building Next.js and AI apps. The videos use an AI-generated voiceover; the code and screen recordings are from my own projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79f6d6538983" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleash Your Code Superpowers: 5 Proven Strategies to Write Cleaner, More Efficient Code!]]></title>
            <link>https://medium.com/@ayubosama416/unleash-your-code-superpowers-5-proven-strategies-to-write-cleaner-more-efficient-code-4d1023b1aedd?source=rss-97e019f2e7c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d1023b1aedd</guid>
            <category><![CDATA[tools-and-resources]]></category>
            <category><![CDATA[case-study]]></category>
            <category><![CDATA[common-pitfalls]]></category>
            <category><![CDATA[team-collaboration]]></category>
            <dc:creator><![CDATA[Osama Ayub]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 12:46:57 GMT</pubDate>
            <atom:updated>2024-02-24T13:52:13.221Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you ready to revolutionize your coding skills and become a true coding ninja? In today’s fast-paced tech world, writing clean and efficient code is crucial for success. Whether you’re a seasoned developer or just starting out, mastering these five game-changing strategies will take your coding game to the next level.</p><ol><li><strong>Simplicity Wins</strong>: The key to writing great code is simplicity. Break down complex problems into smaller, more manageable tasks, and strive to keep your code sleek and straightforward. By eliminating unnecessary complexity, you’ll create code that is easier to understand, debug, and maintain.</li><li><strong>Power of Naming</strong>: Never underestimate the power of a good name. Choose meaningful and descriptive names for your variables, functions, and classes to enhance clarity and understanding. Clear and concise naming not only improves readability but also fosters better collaboration within your team.</li><li><strong>Readability Rules</strong>: A well-formatted and well-commented codebase is a joy to work with. Consistent formatting, indentation, and clear comments make your code easier to read, understand, and maintain. Prioritize readability in your coding style, and you’ll thank yourself (and your teammates) later when it comes time to debug or extend your code.</li><li><strong>Modularity Magic</strong>: Modular code is like building blocks that you can assemble and reuse in different combinations. By breaking your code into independent, reusable components, you’ll improve code organization, promote code reuse, and increase flexibility. Embrace the magic of modularity and watch your codebase become more scalable and maintainable.</li><li><strong>Readability Rules</strong>: A well-formatted and well-commented codebase is a joy to work with. Consistent formatting, indentation, and better comments make your code easier to read, understand, and maintain. Prioritize readability in your coding style, and you’ll thank yourself (and your teammates) later when it comes time to debug or extend your code.</li><li><strong>Refactor Like a Boss</strong>: Refactoring is the secret weapon of top-notch developers. Regularly review and improve your code.</li></ol><p>👉 Ready to elevate your coding to new heights? Dive into these strategies and unlock your full coding potential. Whether you’re a seasoned pro or just starting out, mastering these techniques will help you write cleaner, more efficient code and become a true code ninja. Happy coding! ✨💻</p><p>#CodeNinja #TechTips #SoftwareEngineering #CleanCode #Programming #Developmentbase by eliminating duplication, simplifying complex logic, and improving design patterns. Refactoring isn’t just about making your code cleaner — it’s about continuously striving for excellence and refining your craft.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d1023b1aedd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taking Flight]]></title>
            <link>https://medium.com/@ayubosama416/taking-flight-526a52e32d68?source=rss-97e019f2e7c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/526a52e32d68</guid>
            <category><![CDATA[taking-flight]]></category>
            <category><![CDATA[amal-fellowship]]></category>
            <category><![CDATA[amal-academy]]></category>
            <dc:creator><![CDATA[Osama Ayub]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 20:05:54 GMT</pubDate>
            <atom:updated>2023-10-31T20:05:54.762Z</atom:updated>
            <content:encoded><![CDATA[<p>Last Session at Amal Academy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUsa3ZRSdY1N_R6qljB42g.jpeg" /></figure><p>This Blog would be my last Blog that I’m writing as an Amal Fellow but I hope to continue writing on this platform. So my Journey with Amal Academy started in August 2023 that came to end!. Amal Academy is the platform where I learned alot of new things and made alot of new connections with some amazing people, got a new meaning of life. This would always remain in my heart. Besides working on personal Growth such as working on leadership, problem solving ,team work skills and much more such as good resume ,cover letter and mock interviews apart from this I got a chance to work for social Impact by collecting donations for Edhi Foundation and Akhuwat for the rights of poor people to play a positive role in the society.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Kr18wb9NtqGqY10lZ9yeQ.jpeg" /></figure><p>Though last session was quite emotional for us and the time for us to say Goodbye, but, it was full of learning and encouragement to move forward life. My Instructor Maam Mehak and Maam Aimen shared beautiful tips and pieces of advice on how to implement the things learned in Amal in your professional field. I believe these were really great tips that really gonna help me in my future.</p><p>In my Amal Journey , I made new friends, we called it the Amal Family</p><p>and I will never forget them. They all were motivating, inspiring, caring and supporting individual&#39;s who always help you to grow and excel in your Life. Let me share my personal experience when i was facing problems in my pw and i asked one of my fellow regarding help in that particular task and they helped in finishing the project on time within a week. Especially how can I forget about circle and my circle leader we all worked as a team and completed the Mega Project on time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*mNN3DDqGF0rU3zznjfQgLg.jpeg" /><figcaption>Mega Project Circle</figcaption></figure><p>Though this is the end of the fellowship but actually a start of new journey. This is time to implement all the Amal Learnings in our lives and I already started to implement this such as speaking in front of public ,my values and principles, resume building ,cover letter and In person resume drop.</p><p>After adopting all these techniques i was able to get an internship as Front-End Developer at Ribbash Digital because of learnings Amal Academy and successfully completing it this month and Now looking to start my professional journey in a new software house. I believe these learnings will help me grow in my future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPbzbv2PGvrqT6G9DTyCqg.jpeg" /></figure><p>Thank you Amal Academy for providing me such an amazing opportunity to make new friends, and to grow and excel in my professional journey.</p><p>Thank You Amal Academy!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=526a52e32d68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring your Curiosities Through an Online Course]]></title>
            <link>https://medium.com/@ayubosama416/exploring-your-curiosities-through-an-online-course-c38c30da50f9?source=rss-97e019f2e7c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c38c30da50f9</guid>
            <dc:creator><![CDATA[Osama Ayub]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 17:59:11 GMT</pubDate>
            <atom:updated>2023-10-26T17:59:11.266Z</atom:updated>
            <content:encoded><![CDATA[<p>I have always wanted to learn Fullstack Development and how websites work. Recently, I came across Professional Certfication regarding Front-End Development which is on my future plan. So I thought to go for a course that can explain regarding front-end development for beginners and had background of the topic , and I found Coursera name as Meta Front-End Development course.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnnIT0npytVYfrTzgrIuWg.png" /><figcaption>Front-End developer Course</figcaption></figure><p>when deciding the course I usually look on the reviews and syllabus of the course which were mostly positive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xo9dQZeitv4Og9JDvgGCzw.png" /><figcaption>Review for Course</figcaption></figure><p><strong>My Learnings and Experience with the Course</strong></p><p>The Second Lecture emphasized on Understanding of how the internet works and the essential components that required for the web development. How the data is transferred through different devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rt7af-FES6Y4QaHrP21Kcw.png" /><figcaption>How the web works</figcaption></figure><p>Their last two videos was about the core technologies that are required to become a Front-End Developer and these are a must to learn because these are the building blocks of a web page followed by week 1 quiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sy93wO9EAZOIWDn5pI_dFQ.png" /><figcaption>Core Technologies of web development</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmwnvNYXeUPbktM5vWIwjg.png" /></figure><p>I completed the week 1 quiz by covering all the week 1 content of the course.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhLj8fe5-NcW5GgB36ytcQ.png" /></figure><p>Conclusion:</p><p>While Researching for courses on this topic on Udemy and Coursera and other platforms directly from the experts seemed more beginner friendly and were to completed at your own pace. I’ve enjoyed the videos ,quizzes of the course so far.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c38c30da50f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing My Experience]]></title>
            <link>https://medium.com/@ayubosama416/visualizing-my-experience-24690238df8c?source=rss-97e019f2e7c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/24690238df8c</guid>
            <category><![CDATA[visualizing-experience]]></category>
            <dc:creator><![CDATA[Osama Ayub]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 18:13:56 GMT</pubDate>
            <atom:updated>2023-10-23T18:13:56.041Z</atom:updated>
            <content:encoded><![CDATA[<p>Before starting the Amal Career Prep Fellowship, I was hesitant and confused about my goals. At Amal, I realized that compassion is not enough — you must act. I identified my personal and professional goals, as well as the “WHY” for them. This task forced me to reflect on my values and motivations.</p><p>“Nothing is as important as passion. No matter what you want to do with your life, be passionate.” — Jon Bon Jovi</p><p>In the first week of the fellowship, we were tasked with identifying our personal and professional goals. Most people have some aims and goals in their lives, but very few people know the reason behind setting those goals. I also had a few aims, but I had never thought about why I wanted to achieve them. The interesting part of this task was that we had to find our personal and professional goals, as well as the “WHY” for those goals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*R1LmKLiUej5wibt2.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24690238df8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Positive Reflections]]></title>
            <link>https://medium.com/@ayubosama416/positive-reflections-c72ef837b8e9?source=rss-97e019f2e7c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c72ef837b8e9</guid>
            <category><![CDATA[positive-reflection]]></category>
            <dc:creator><![CDATA[Osama Ayub]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 17:58:02 GMT</pubDate>
            <atom:updated>2023-10-19T18:01:03.627Z</atom:updated>
            <content:encoded><![CDATA[<p>It was about two and a half months ago when I received a confirmation email for the fellowship from Amal Academy. In my admission interview, I was asked why I wanted to appear for this fellowship program, as by the books, I am an experienced person. I answered the panel that it would be a win-win for me and my fellow fellows. I would get a chance to converse with the young guns, and maybe they could take something from my exposure. Luckily, I was selected, and believe me, these were the most thoughtful days of my life. I never pondered whether I needed a mentor or something. It was me who was curious about mentoring undergraduates. But inculcating in the program made me realize there is no particular age bracket for learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*BoPoPPCzneRvRdVWczognA.png" /><figcaption>Amal Academy</figcaption></figure><p>I am still considering the fact that the last 70 to 80 days were a roller coaster ride for me as I immersed myself into various kinds of activities and project works that somehow sharpened my rusted brain. Amongst numerous live sessions, group discussions, and offline tasks, I seriously think a one-on-one session with Ma’am Aimen marked a dent in my processing methodology. The session originally was scheduled for 15 mins only but ended up almost after 45 mins. The best part was most of the time, I was listening quietly and was trying to understand to what Ma’am Aimen was saying. That conversation created a profound effect on me as I am still in the process of transformation. The talk was a gift for me from her. It was a road map for me regarding my prospects. I was struggling with what is the future for me if I want to do the same job or start some entrepreneurship or do some freelancing. The answer was a big question mark and Ma’am hit me with the same queries. I replied I am confused. She then came up with a plan and suggested starting with positivity. Let the energy come in. Firstly, thankful to Allah SWT, you have a job and a good living standard. Now make a roadmap, start thinking about what you need to do and then embark on the journey to achieve it. Researching for the goals and meeting up with the people already in the area where you want to go is the most important perimeter to gauge first and then work on it vigorously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*1B2DMKABTx0UzJTLDba_aw.png" /><figcaption>Youth Realize Dreams</figcaption></figure><p>I am amazed by the positive attitude and the liveliness which she possessed throughout the session. She gave me some key points which I need to work on and gradually, I will be improving and should be on a path to success. I started believing in myself which probably, I was losing before the session and the encounter worked as a great tool for me. I am now focused on the fact that I need to earn a degree in Computer Science if I want to excel professionally and that is final.</p><p>Amal Principle of Khudi</p><p>Looking back for three months, I feel sad for myself because I thought my current job is the only thing left for me. And according to Sir Nizami, even the sky is not the limit. This world is for me and I can do whatever I think. There is no limitation to the human mind and since engineering is a versatile field, I can roam anywhere with freedom. I am grateful to the entire team of Amal Academy. You, people, are doing an excellent job, and my facilitators Aimen Qadeer and Mehak Mazhar, and last but not least my fellow fellows. You people are giving me memories worth remembering with loads and loads of learning. Thank you, Amal!</p><p>#postiveReflections #Amal Academy</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c72ef837b8e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Meeting with mentor]]></title>
            <link>https://medium.com/@ayubosama416/meeting-with-mentor-cf68bab0e042?source=rss-97e019f2e7c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf68bab0e042</guid>
            <category><![CDATA[mentorship]]></category>
            <dc:creator><![CDATA[Osama Ayub]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 18:29:14 GMT</pubDate>
            <atom:updated>2023-10-11T18:29:14.522Z</atom:updated>
            <content:encoded><![CDATA[<p>Dear Sir Bilal,</p><p>I hope this email finds you in good health and spirits. I am writing to express my heartfelt gratitude for your guidance and mentorship during my internship at Ribbash Digital. Your support and encouragement have been crucial to my growth and development as a professional.</p><p>During my internship, I have learned many invaluable lessons from you, and I wish to acknowledge one that stands out the most. Your emphasis on working smarter, not harder, has been a game-changer for me. Previously, I used to focus on putting in long hours, but now I realize how essential it is to be efficient and concentrate on tasks that have a greater impact. I have learned to measure my results without taking into account the time taken, which has helped me stay focused and track my progress effectively.</p><p>Your advice on finding one’s purpose in life has also been instrumental in my growth. I am still exploring my interests and passions, but your story has inspired me to continue seeking out my true calling. I am determined to find a career that I am passionate about and that makes a difference in the world.</p><p>I am thrilled to inform you that I have made significant progress on my internship projects. I have successfully developed a new landing page for our client’s website, and I am currently working on implementing a new e-commerce platform. I am confident that I can complete both of these projects on time and to a high standard.</p><p>I am grateful for the opportunity to learn and grow at Ribbash Digital. I am committed to becoming a top-performing front-end developer, and I am confident that I can achieve this goal with your continued support.</p><p>Once again, I express my sincere gratitude to you, Sir Bilal, for everything. I am looking forward to our future meetings.</p><p>Best regards,<br>Osama Ayub</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf68bab0e042" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>