Quick Start
Next.js Setup
Install
Let's start by installing the required packages.
- npm
- pnpm
- yarn
shell
npm install @edgestore/server @edgestore/react zod
shell
pnpm add @edgestore/server @edgestore/react zod
shell
yarn add @edgestore/server @edgestore/react zod
Environment Variables
Then go to your Dashboard, create a new project and copy the keys to your environment variables.
.envshell
EDGE_STORE_ACCESS_KEY=your-access-keyEDGE_STORE_SECRET_KEY=your-secret-key
Make sure you add .env
to your .gitignore
file.
You don't want to commit your secrets keys to your repository.
Backend
Now we can create the backend code for our Next.js app.
Edge Store is compatible with both types of Next.js apps (pages router
and app router
).
The example below is the simplest bucket you can create with Edge Store. Just a simple file bucket with no validation that will be accessible by anyone with the link.
You can have multiple buckets in your app, each with its own configuration.
- app
- pages
src/app/api/edgestore/[...edgestore]/route.tsts
import {initEdgeStore } from '@edgestore/server';import {createEdgeStoreNextHandler } from '@edgestore/server/adapters/next/app';constes =initEdgeStore .create ();/*** This is the main router for the Edge Store buckets.*/constedgeStoreRouter =es .router ({publicFiles :es .fileBucket (),});consthandler =createEdgeStoreNextHandler ({router :edgeStoreRouter ,});export {handler asGET ,handler asPOST };/*** This type is used to create the type-safe client for the frontend.*/export typeEdgeStoreRouter = typeofedgeStoreRouter ;
src/pages/api/edgestore/[...edgestore].tstsx
import { initEdgeStore } from '@edgestore/server';import { createEdgeStoreNextHandler } from '@edgestore/server/adapters/next/pages';const es = initEdgeStore.create();/*** This is the main router for the edgestore buckets.*/const edgeStoreRouter = es.router({publicFiles: es.fileBucket(),});export default createEdgeStoreNextHandler({router: edgeStoreRouter,});/*** This type is used to create the type-safe client for the frontend.*/export type EdgeStoreRouter = typeof edgeStoreRouter;
Frontend
Now let's initiate our context provider.
- app
- pages
src/lib/edgestore.tstsx
'use client';import { typeEdgeStoreRouter } from '../app/api/edgestore/[...edgestore]/route';import {createEdgeStoreProvider } from '@edgestore/react';const {EdgeStoreProvider ,useEdgeStore } =createEdgeStoreProvider <EdgeStoreRouter >();export {EdgeStoreProvider ,useEdgeStore };
src/lib/edgestore.tstsx
'use client';import { createEdgeStoreProvider } from '@edgestore/react';import { type EdgeStoreRouter } from '../pages/api/edgestore/[...edgestore]';const { EdgeStoreProvider, useEdgeStore } =createEdgeStoreProvider<EdgeStoreRouter>();export { EdgeStoreProvider, useEdgeStore };
And then wrap our app with the provider.
- app
- pages
src/app/layout.tsxtsx
import { EdgeStoreProvider } from '../lib/edgestore';import './globals.css';// ...export default function RootLayout({children,}: {children: React.ReactNode;}) {return (<html lang="en"><body><EdgeStoreProvider>{children}</EdgeStoreProvider></body></html>);}
src/pages/_app.tsxtsx
import '../styles/globals.css';import type { AppProps } from 'next/app';import { EdgeStoreProvider } from '../lib/edgestore';export default function App({ Component, pageProps }: AppProps) {return (<EdgeStoreProvider><Component {...pageProps} /></EdgeStoreProvider>);}
Upload file
You can use the useEdgeStore
hook to access type-safe frontend client and use it to upload files.
tsx
'use client';import * asReact from 'react';import {useEdgeStore } from '../lib/edgestore';export default functionPage () {const [file ,setFile ] =React .useState <File >();const {edgestore } =useEdgeStore ();return (<div ><input type ="file"onChange ={(e ) => {setFile (e .target .files ?.[0]);}}/><button onClick ={async () => {if (file ) {constres = awaitedgestore .publicFiles .upload ({file ,onProgressChange : (progress ) => {// you can use this to show a progress barconsole .log (progress );},});// you can run some server action or api here// to add the necessary data to your databaseconsole .log (res );}}}>Upload</button ></div >);}
Replace file
By passing the replaceTargetUrl
option, you can replace an existing file with a new one.
It will automatically delete the old file after the upload is complete.
You can also just upload the file using the same file name, but in that case, you might still see the old file for a while because of the CDN cache.
tsx
const res = await edgestore.publicFiles.upload({file,options: {replaceTargetUrl: oldFileUrl,},// ...});
Delete file
You can delete a file by passing its url to the delete
method.
To be able to delete a file from a client component like this, you will need to set the beforeDelete
lifecycle hook on the bucket.
tsx
await edgestore.publicFiles.delete({url: urlToDelete,});
Cancel upload
To cancel an ongoing file upload, you can use an AbortController the same way you would use it to cancel a fetch request.
tsx
// prepare a state for the AbortControllerconst [abortController, setAbortController] = useState<AbortController>();// ...// instantiate the AbortController and add the signal to the upload methodconst abortController = new AbortController();setAbortController(abortController);const res = await edgestore.publicFiles.upload({file,signal: abortController.signal,});// ...// to cancel the upload, call the controller's abort methodabortController?.abort();
When you cancel an upload, an UploadAbortedError
will be thrown.
You can catch this error and handle it as needed.
For more information, check the Error Handling page.
Temporary files
You can upload temporary files by passing the temporary
option to the upload
method.
Temporary files will be automatically deleted after 24 hours if they are not confirmed.
tsx
await edgestore.publicFiles.upload({file: fileToUpload,options: {temporary: true,},});
To confirm a temporary file, you can use the confirmUpload
method.
tsx
await edgestore.publicFiles.confirmUpload({url: urlToConfirm,});
You can check if a file is temporary in the dashboard.
Temporary files are marked with a clock icon.
Troubleshooting
If you have any problems using Edge Store, please check the Troubleshooting page.