npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-fun

v1.0.4

Published

Inline Server-Side Functions for Next.js

Downloads

18

Readme

NextFun

Inline Serverside functions for next.js page routes,

What?

next-fun is a way to execute inline functions on your server without compromises. just add $ to any function in your page routes and it'll automatically become a serverside function.

Why?

I've been working on a project for a while now and I've found myself writing a lot of code in the api route. I wanted to make it easier to write and maintain mini server-side code.

How?

  1. Install
npm install -i next-fun
yarn add next-fun
  1. Configure next-fun on your next.config.js file
const {withNextFun} = require("next-fun");

module.exports = withNextFun({
    //other configs
})
  1. Create a function on your page route, e.x
async function $say_hi(){
    console.log("I'm on your server's console, yay!")
    return `Hie, say magic.`
}

export default function Home() {
    return <button onClick={async ()=>{
        alert(await $say_hi())
    }}>
    
    </button>
}

This is a normal function, it takes no arguments, returns a string. except it must be asynchronously called, should not get or set any state directly & the function name should be prefixed with $ (e.x $say_hi) as it's the only way next-fun could identify that it's a server-side function.


In three steps, you now have the ability to define server-side functions for your page routes.

Example

Blogs

async function $like_post(post_id){
    // you have a req object, you can use it to get the cookies, session, etc.
    const fetch = require("node-fetch")
    const user = req.session.user_id
    const status = await (await fetch(`${process.env.base_cms_url}/action/like`, {
        method: "POST",
        body: JSON.stringify({ 
            post_id,
            user
        }),
        headers: {
            "Content-Type": "application/json",
        }
    }).json())
    return status.success === true
}

export default function Post() {
    return <div>
    <h1>Banana Mania</h1>
    <article>I love bananas, they are not the type of things I enjoy mostly, but still who gives a darn f##k.</article>
    <button onClick={async ()=>{
        if(await $like_post("banana-mania")){
            alert("You like bananas!")
        }else{
            alert("Something went wrong!")
        }
    }}>Like</button>
    </div>
}

Yay, we created a blog operation without an api route & it looks like a normal function.

Newsletter subscription

async function $subscribe(email){
    // you have a req object, you can use it to get the cookies, session, etc.
    try{
const {subscribtionModel} = require("/db/models")
    subscribtionModel.create({
        email,
    }).then(subscribtion => {
        return subscribtion.save()
    })  
    return true
    }catch(e){
return false;
    }
    
}

export default function Home() {
    return <div>
    <h1>Aloha, ?!</h1>
    <article>The worst website ever, but you might still want to be uptodate.</article>
    <section>
    <h3>Subscribe</h3>
    <input type="email" id="email_input" placeholder="email"/>
    <button onClick={async ()=>{
        if(await $subscribe(document.getElementById("email_input").value))){
            alert("We'll let you know of anything.")
        }else{
            alert("Something went wrong!")
        }
    }}>Subscribe</button>
    </section>
    
    </div>
}

Security Concerns.

Thinks about this as normal api routes, except you can call it directly as a normal function.

As per that, there's not that much of securtity concern, but if you're using this in a production environment, you should make sure you have csrf tokens validation in place, I might make a default csrf validator for next-fun in the future, but for now, you need to do it yourself.

You should make sure you have all your api tokens in your environment file, so that you don't have to worry about them being leaked.

  • Will my api tokens be exposed to the client?
    • No, they are not exposed to the client, they are only exposed to the server, so you can't access them from the client, unless you returned the process.env.token from the server side function.
  • Why is this better than api routes.
    • Writing too many api routes is just f***ed up, I for ex had around 100 api routes in my project, and I was getting tired of writing them (creating a new route for each api route was just too much).
  • Why can't I access local variables of the client?
    • I've gone through this question & at basic it's not a good idea to mutate a state from the server side, it creates a wide open security hole, local variables are meant to be predictable, if you accessed a local variable from the server it might replace a value in the server's variables, i.e (process.env.base_url), now see what that creates.
  • Can I use this in a production environment?
    • If you know what you're doing, yes you can.

Faqs

  • How does it work?
    • Next-Fun replaces any function in the /pages/...(.js|.jsx) route with a function of the same name & creates an api route in /api/execute/{file_name}{function_name}{level}.js, & it calls that as a normal fetch request, await it and return the response as either json or string.

License

MIT You can use this in any project, but you should keep the license & copyright. I'm not responsible for any damage caused by this.