How to retrieve a record with airtable js and nextjs

Hiya,
I’m using nextjs and using the airtable npm package.

I have an emails table and I want to check whether I already have an email in the base so thought I could try to retrieve one. Firstly…this seems like a GET but with a body…? Does that work?
Secondly, what am i doing wrong here?

When i try and test it in postman it doesnt work but i’m not sure what i need to do. Help would be appreciated!

Hello!

You’ve probably figured this out by now but you should be using the query object instead of body when doing GET requests.
Also, I don’t know how your utils/Airtable is structured but if you’re using the original find method from Airtable.js, it won’t work because it expects a record ID. You can try logging the error to see the details and confirm if that’s really the error.

To find records by some other column, you can use the select method and pass a formula to the filterByFormula property. I’ll show you an example of mine.

import type { NextApiRequest, NextApiResponse } from 'next';
import Airtable from 'airtable';

type Notification = {
  id: string;
  name: string;
  image: string;
  sender: {
    id: string;
    name: string;
    email: string;
  },
  contentUrl: string;
}

async function handler (request: NextApiRequest, response: NextApiResponse) {
  if (request.method !== 'GET') {
    return response.status(405).json({ message: 'Method should be GET' });
  }

  const base = Airtable.base(process.env.AIRTABLE_NOTIFICATION_BASE!);
  const table = base('Notifications').select({
    view: 'Data',
    filterByFormula: `{URL} = "${request.query.url}"`,
    fields: ['Name', 'Image', 'StartAt', 'Sender', 'URL']
  });
  const notifications: Notification[] = [];

  try {
    await table.eachPage((records, processNextPage) => {
      records.forEach(({ fields, id }) => {
        notifications.push({
          id,
          image: (fields.Image as any[])[0].thumbnails.large.url,
          name: fields.Name as Notification['name'],
          sender: fields.Sender as Notification['sender'],
          contentUrl: fields.URL as Notification['contentUrl']
        })
      });
      processNextPage();
    });
  } catch (error) {
    console.log(error);
    return response.status(502).json({ message: 'Unknown server error' });
  }
    
  return response.status(200).json({ notifications });
}

export default handler;

Basically, I’m passing a url query parameter from the frontend and using it to build a formula for filtering. It’ll return an array containing any record that matches it so if that column value isn’t unique, it’ll bring multiple results.

I’m pretty new to Airtable so maybe there’s a better way, but that’s how I’ve initially tried it.

1 Like

This topic was solved and automatically closed 15 days after the last reply. New replies are no longer allowed.