Seamlessly Upload Images from React Native/Expo to an Elysia API

Elysia API for TypeScript Enthusiasts

Elysia API for TypeScript Enthusiasts

Elysia is a robust API framework tailored for TypeScript developers, emphasizing end-to-end type safety, type integrity, and an exceptional developer experience. Powered by Bun, Elysia also integrates seamlessly with TypeBox for request validation. This built-in support eliminates the need to manually configure validation libraries like Yup or Joi. However, when working with React Native apps, developers often encounter challenges uploading images. Here’s how to resolve this issue.

Getting Started with Elysia

To illustrate, let’s begin with a simple API setup in Elysia:

import { Elysia, t } from 'elysia'; 
 
new Elysia() 
  .post( 
    '/upload', 
    ({ body }) => { 
      // Process the uploaded file 
    }, 
    { 
      body: t.Object({ 
        file: t.File(), 
      }), 
    } 
  ) 
  .listen(3000);

In this example, Elysia’s built-in type system automatically identifies the multipart/form-data content type, simplifying file uploads. But when paired with React Native, this setup might result in errors. Let’s fix that.

1. Installing Elysia

Follow these steps to set up Elysia:

# Create a new project 
bun create elysia my-elysia-app 
 
# Navigate into the project directory 
cd my-elysia-app 
 
# Install dependencies 
bun install

2. Start the Development Server

Run the server:

bun dev

3. Setting Up the Elysia Endpoint

Here’s a refined endpoint for handling image uploads:

import { Elysia, t } from 'elysia'; 
 
const app = new Elysia().post( 
  '/', 
  async ({ body }) => { 
    const fileBuffer = Buffer.from(await body?.files.arrayBuffer()); 
 
    // Logic for uploading the file to object storage 
    const imageUrl = "your-storage-url"; // Replace with actual logic 
 
    return { 
      message: "Image uploaded successfully", 
      data: { 
        imageUrl, 
      }, 
    }; 
  }, 
  { 
    body: t.Object({ 
      file: t.Files(), 
    }), 
  } 
) 
.listen(3000);

This endpoint processes the uploaded file and stores it in object storage. But the challenge lies in integrating this with React Native.

4. Integrating Image Upload in React Native

Using the react-native-image-picker library simplifies image selection and upload from a React Native app:

import { launchImageLibrary } from 'react-native-image-picker'; 
 
const onImagePress = async () => { 
  const formData = new FormData(); 
 
  const result = await launchImageLibrary({ 
    mediaType: 'photo', 
  }); 
 
  if (result?.assets && result?.assets[0]?.uri) { 
    const fileName = result.assets[0].uri.split('/').pop(); 
 
    if (!fileName || !result.assets[0].uri) return; 
 
    formData.append('file', { 
      uri: result.assets[0].uri, 
      name: fileName, 
      type: 'image/jpg', 
    } as unknown as Blob); 
 
    try { 
      const response = await uploadImage(formData); 
      console.log('Image upload response:', response); 
    } catch (error) { 
      console.error('Error uploading image:', error); 
    } 
  } 
}; 
 
const uploadImage = async (formData: FormData) => { 
  const response = await fetch('http://localhost:3000', { 
    method: 'POST', 
    body: formData, 
  }); 
 
  return response.json(); 
};

Key Points

  1. Image Selection: Use react-native-image-picker to let users choose an image(Feel free to use any other image picker libraries!).
  2. FormData: Append the selected image to a FormData object for upload.
  3. Fetch API: Use fetch for the API call instead of Elysia Eden, as Eden may not handle React Native's file format correctly.

The Workaround for React Native

While Elysia works seamlessly for web applications, integrating it directly with React Native for file uploads can be tricky due to file format differences. This workaround ensures type safety on both the client and server sides, preserving Elysia’s core strengths.

Conclusion

Elysia is an excellent framework for TypeScript developers, delivering unmatched type safety and developer experience. While React Native integration requires a slight adjustment for file uploads, the framework’s flexibility and performance make it a top choice for modern API development. Future updates might streamline this further, making Elysia even more versatile.

Try BanKan Board — The Project Management App Made for Developers, by Developers

If you’re tired of complicated project management tools with story points, sprints, and endless processes, BanKan Board is here to simplify your workflow. Built with developers in mind, BanKan Board lets you manage your projects without the clutter.

Key Features:

  • No complicated processes: Focus on what matters without the overhead of traditional project management systems.
  • Claude AI Assistant: Get smart assistance to streamline your tasks and improve productivity.
  • Free to Use: Start using it without any upfront cost.
  • Premium Features: Upgrade to unlock advanced functionality tailored to your team’s needs.

Whether you’re building a side project, managing a team, or collaborating on open-source software, BanKan Board is designed to make your life easier. Try it today!

Get Started with BanKan Board — It’s Free!