Search code examples
next.jssupabasesupabase-js

How to get the id of last insert in nextjs/supabase


With my current project i'm using supabase and nextjs. Something weird is occurring, after inserting a row into a table i want to get the id of said row, but it does not work and i have no idea why.

import { supabase } from '../utils/supabaseClient';

export default function TestSupabase() {
    const testSupabaseConnection = async () => {
        try {
            const { data, error } = await supabase
                .from('your_table')
                .insert([{ column1: 'value1', column2: 'value2' }]);
            
            console.log('Data:', data, 'Error:', error);
        } catch (err) {
            console.error('Unexpected Error:', err);
        }
    };
    

    return (
        <div>
            <h1>Supabase Konfigurationstest</h1>
            <button onClick={testSupabaseConnection}>Teste Supabase-Verbindung</button>
        </div>
    );
}
// utils/supabaseClient.js
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
export const supabase = createClient(supabaseUrl, supabaseKey);
{
  "name": "goatlib",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@ericblade/quagga2": "^1.8.4",
    "@heroicons/react": "^1.0.6",
    "@supabase/supabase-js": "^2.39.2",
    "next": "14.0.4",
    "react": "^18",
    "react-dom": "^18"
  },
  "devDependencies": {
    "autoprefixer": "^10.0.1",
    "eslint": "^8",
    "eslint-config-next": "14.0.4",
    "postcss": "^8",
    "tailwindcss": "^3.3.0"
  }
}

console Output is: Data: null Error: null although the row is inserted always. The code above is basically out of the docs.


Solution

  • After your query you need to add select like this:

    const { data, error } = await supabase
    .from('your_table')
    .insert([{ column1: 'value1', column2: 'value2' }])
    .select();
    

    If you just want the id you can include it in your select braket