Construct a file storage system with Cloudinary + Auth0




File internet hosting and synchronization companies like Google Drive, OneDrive, iCloud, e.t.c permit customers to retailer recordsdata within the cloud, synchronize recordsdata throughout units, and share recordsdata. They assist save house on units by digitizing recordsdata, integrating storage, and supporting distant entry.

On this put up, we are going to focus on the right way to construct a customized and safe file storage system utilizing Cloudinary, Auth0, and Next.js. On the finish of this tutorial, we’d have learnt the right way to host recordsdata on Cloudinary by tag, serve recordsdata and safe the web software utilizing Auth0.

By the use of introduction, Cloudinary is a platform on which you’ll shortly and simply add, retailer, handle, remodel, and ship pictures and movies for web sites and apps. The platform additionally provides an unlimited assortment of SDKs for frontend frameworks and libraries.

Auth0 is a platform that gives programs to quickly combine authentication and authorization for web, cellular, and legacy purposes.

Subsequent.js is a React-based front-end development framework that allows functionalities like server-side rendering, static website technology, file-system routing (without having to manually configure react-router-dom), and API endpoints for backend options.



Supply code

You will discover the supply code of this mission here.

The following steps on this put up require JavaScript and React.js expertise. Expertise with Subsequent.js isn’t a requirement, however it’s good to have.

We additionally want the next:



Getting Began

We have to create a Subsequent.js starter mission by navigating to the specified listing and operating the command under in our terminal

npx create-next-app mini_drive && cd mini_drive
Enter fullscreen mode

Exit fullscreen mode

This command creates a Subsequent.js mission known as mini_drive and navigates into the mission listing.

We proceed to put in the required dependencies with:

npm set up react-helmet cloudinary-react @auth0/nextjs-auth0 axios
Enter fullscreen mode

Exit fullscreen mode

react-helmet is a library that takes plain HTML tags and outputs plain HTML tags. It is going to assist us keep away from the Reference error: Window will not be Outlined error when utilizing client-side solely packages in Subsequent.js.

cloudinary-react is a library that handles rendering of media recordsdata.

@auth0/nextjs-auth0 is a library for implementing person authentication in Subsequent.js purposes.

axios is a library that handles http calls.

With the mission dependencies put in, we are able to leverage Subsequent.js CSS Module help to fashion our web page by changing the content material in Residence.module.css within the kinds folder with the gist under:

With that carried out, we are able to replace index.js file within the pages folder by importing the kinds created and configure Cloudinary Add Widget to add recordsdata to Cloudinary. We additionally embody state variables to deal with:

  • Altering tabs between pictures, movies and recordsdata
  • The filetype to be uploaded(pictures, movies or recordsdata). We’ll use this to tag our add
  • The returned url.
    import { Helmet } from 'react-helmet';
    import kinds from '../kinds/Residence.module.css';
    import { useState } from 'react';

    export default perform Residence() {
      const [tab, setTab] = useState(1);
      const [filetype, setFiletype] = useState('');
      const [url, setURL] = useState(null);

      const handleChange = (e) => {
        setFiletype(e.goal.worth);
      };

      const openWidget = () => {
        window.cloudinary
          .createUploadWidget(
            {
              cloudName: 'dtgbzmpca',
              uploadPreset: 'tca2j0ee',
              tags: [filetype],
            },
            (error, outcome) => {
              if (!error && outcome && outcome.occasion === 'success') {
                setURL(outcome.information.url);
              }
            }
          )
          .open();
      };

      const handleSubmit = (e) => {
        e.preventDefault();
        openWidget();
      };

      return (
        <div>
          <Helmet>
            <script src='https://upload-widget.cloudinary.com/international/all.js' />
          </Helmet>
          {/* remaining JSX comes right here */}
        </div>
      );
    }
Enter fullscreen mode

Exit fullscreen mode

The Cloudinary Add Widget additionally configures cloudName uploadPreset and tag. The cloudname is the title of our Cloudinary account, uploadPreset is a parameter that allows us to centrally outline a set of asset add choices as a substitute of specifying them in every add name and tags (highlighted above) are key phrases to make recordsdata extra searchable. tags will turn out to be useful when separating our recordsdata into tabs and up to date the url with returned URL. Lastly, we used react-helmet so as to add Cloudinary Add Widget CDN to the applying.

To create a brand new add preset, click on on the Settings Icon, choose the Add tab, navigate to the Add presets part, click on on the Add Add preset.

select preset

copy preset name, change to Unsigned and save

Discover out extra about Cloudinary Add Widget here.

Then we have to embody our markup for type and tabs as proven under.

With that carried out, we are able to begin a development server utilizing the command under:

npm run dev
Enter fullscreen mode

Exit fullscreen mode

running application



Including elements to deal with pictures, movies and recordsdata

To show our recordsdata, we have to create a elements folder within the root listing and, within the folder, create an ImageList.js, VideoList.js, and FileList.js recordsdata and add the code snippet under respectively.

ImageList.js

VideoList.js

FileList.js

The above snippets carry out these duties respectively:

  • Import the required dependencies.
  • Create a part that takes url as a prop.
  • Create states to handle loading, error and returned checklist.
  • Use the useEffect hooks to get checklist of sources matching the required tag and replace state accordingly.
    The Cloudinary URL follows this format

http://res.cloudinary.com/<your_cloud_name>/<resource_type>/checklist/<tag>.json

<your_cloud_name> is the title of our Cloudinary account.
<resource_type> is the useful resource kind. picture, video, and uncooked in our case.
<tag> is to get the checklist of sources matching the tag. pictures, movies, and recordsdata in our case

  • Conditionally render the returned checklist of Pictures and Movies utilizing cloudinary-react and checklist of recordsdata.

Lastly, we have to import the elements and embody them contained in the index.js

Up to date Index.js



Cloudinary Restricted Media Sorts

In different to guard our account and quotas from being abused or misused by others. Cloudinary restricts creation of recent sources by way of unsigned requests. Earlier than we begin testing our software, we have to disable Useful resource Listing in our Cloudinary console.

To do that, we have to login into our Cloudinary account, click on on the settings icon, choose the Safety tab, and uncheck the Useful resource Listing possibility, then scroll right down to the underside of the web page and Save

Resource List.

Lastly, we are able to check our software by deciding on the media kind, importing recordsdata and think about them on totally different tabs.



Setup a Developer Account

To get began, we have to log into our Auth0 dashboard. Click on on Functions

Auth0 Dashboard

Within the software web page, click on on the Create Software button, enter software title auth0Cloudinary in our case, choose Common Web Software as the applying kind and Create

Creating a new app

Click on on the Settings tab and duplicate the Area, Shopper ID, and Shopper Secret.

copy credentials

Then scroll right down to the Functions URIs part and fill within the particulars under for Allowed Callback URLs and Allowed Logout URLs, respectively.

  • Allowed Callback URLs
    • http://localhost:3000/api/auth/callback
  • Allowed Logout URLs
    • http://localhost:3000/
      URIs

Then scroll right down to the underside of the web page and click on on the Save Adjustments button*.*



Integrating Auth0 with Subsequent.js

To combine Auth0 in our software, we have to create an .env.native file in our root listing and fill within the required parameters(Area, Shopper ID and Shopper Secret) as proven under:

AUTH0_SECRET='LONG_RANDOM_VALUE'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='https://YOUR_AUTH0_DOMAIN.auth0.com'
AUTH0_CLIENT_ID='YOUR_AUTH0_CLIENT_ID'
AUTH0_CLIENT_SECRET='YOUR_AUTH0_CLIENT_SECRET'
Enter fullscreen mode

Exit fullscreen mode

We are able to run the snippet under on our terminal to generate a random secret for the AUTH0_SECRET

node -e "console.log(crypto.randomBytes(32).toString('hex'))"
Enter fullscreen mode

Exit fullscreen mode

Subsequent, we have to create a dynamic route file for our APIs. We have to navigate to the pages folder, inside this folder, navigate to the api folder, within the folder, create an auth folder, and inside this folder, create an […auth0].js file and add the snippet under:

    import { handleAuth } from '@auth0/nextjs-auth0';
    export default handleAuth();
Enter fullscreen mode

Exit fullscreen mode

The handleAuth() perform will generate APIs for:

  • Login
  • Logout
  • Fetch person information
  • Redirect person on profitable login.

Subsequent, we have to replace _app.js file contained in the pages folder as proven under:

    import { UserProvider } from '@auth0/nextjs-auth0';
    export default perform App({ Part, pageProps }) {
      return (
        <UserProvider>
          <Part {...pageProps} />
        </UserProvider>
      );
    }
Enter fullscreen mode

Exit fullscreen mode

Lastly, we have to replace index.js as proven under

    //different imports right here
    import { withPageAuthRequired } from '@auth0/nextjs-auth0';

    export default perform Residence({ person }) { //replace this with destructure props
      //state goes right here

      //features goes right here

      return (
        <div>
          <Helmet>
            <script src='https://upload-widget.cloudinary.com/international/all.js' />
          </Helmet>
          <fundamental className={kinds.recordsdata}>
            <header className={kinds.header}>
              <a href='/api/auth/logout' className={kinds.logout}> {/* add href to this*/}
                Log Out
              </a>
            </header>
            <p className={kinds.title}>Hello {person.title}</p> {/*add this*/}
            {/*remaining code snippet goes right here*/}
          </fundamental>
        </div>
      );
    }
    export const getServerSideProps = withPageAuthRequired({
      returnTo: '/',
    });
Enter fullscreen mode

Exit fullscreen mode

Within the snippet above, we imported withPageAuthRequired and in addition modified the log off hyperlink. We used Subsequent.js inbuilt methodology getServerSideProps to name the withPageAuthRequired methodology, specified the URL to redirect to after login, accessed the person props it returned after which displayed the person’s title.

Full index.js

We are able to check our software by beginning the development server once more, join, after which log in to entry our software.

This put up mentioned the right way to construct a customized and safe file storage system utilizing Cloudinary, Auth0, and Subsequent.js.

You could discover these sources helpful:

Content material created for the Hackmamba Jamstack Content material Hackathon.



Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#Construct #file #storage #system #Cloudinary #Auth0